All files / src/libs https.js

74.19% Statements 23/31
87.5% Branches 14/16
83.33% Functions 5/6
74.19% Lines 23/31
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61        3x 3x 3x 1x 1x           3x 3x   3x 3x 3x   3x 3x 3x         3x 1x 1x             1x 1x             2x       3x       3x 1x   3x        
import https from 'https';
 
export default class customHttps {
  static request (options) {
    const requestParams = Object.assign({}, options);
    return new Promise((resolve, reject) => {
      if (('body' in requestParams) === true && requestParams.body !== null) {
        requestParams.body = JSON.stringify(requestParams.body);
        requestParams.headers = Object.assign({
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(requestParams.body)
        }, requestParams.headers);
      }
 
      const request = https.request(requestParams, (response) => {
        let currentBody = [];
 
        response.setEncoding('utf8');
        response.on('data', (chunk) => {
          currentBody.push(chunk);
        });
        response.on('end', () => {
          try {
            currentBody = JSON.parse(currentBody.join(''));
          } catch (e) {
            currentBody = '';
          }
 
          if ([200, 201, 204].includes(response.statusCode) === false) {
            Eif (currentBody && ('error' in currentBody) === true) {
              Iif (Object.prototype.toString.call(currentBody.error) === '[object Object]') {
                const fieldsError = new Error('invalid body');
                fieldsError.fields = currentBody.error;
                reject(fieldsError);
                return;
              }
 
              reject(new Error(currentBody.error));
              return;
            }
 
            reject(new Error(response.statusCode));
            return;
          }
 
          resolve(currentBody);
        });
      });
 
      request.on('error', (error) => {
        reject(error);
      });
 
      if (('body' in requestParams) === true && requestParams.body !== null) {
        request.write(requestParams.body);
      }
      request.end();
    });
  }
}