All files http.js

88% Statements 22/25
100% Branches 8/8
77.78% Functions 7/9
91.3% Lines 21/23
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 62 63 64                7x 6x 6x                     6x 5x   5x 1x       5x   5x   5x 5x 5x 5x 1x   4x                     6x 5x 5x           6x 6x 5x      
import http from 'https';
 
/**
 * Creates an http endpoint object that we can then call
 * @param  {String} [endpoint='event']        the endpoint we should hit from the base url
 * @param  {String} [method='POST']           the type of request we should make
 * @return {Promise}
 */
export default (endpoint = '/v1/event', method = 'POST') => (apikey, bod) => (
  new Promise((resolve, reject) => {
    const options = {
      host: 'api.utu.ai',
      path: endpoint,
      method,
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache',
        apikey,
      },
    };
 
    const request = http.request(options, (res) => {
      let error = false;
      // handle http errors
      if (res.statusCode < 200 || res.statusCode > 299) {
        error = true;
      }
 
      // temporary data holder
      const body = [];
      // on every content chunk, push it to the data array
      res.on('data', (chunk) => body.push(chunk));
      // we are done, resolve promise with those joined chunks
      res.on('end', () => {
        try {
          const b = JSON.parse(body.join(''));
          if (error) {
            reject(b);
          } else {
            resolve(b);
          }
        } catch (e) {
          reject({
            error: e,
            body: body.join(''),
          });
        }
      });
    });
 
    request.on('socket', (socket) => {
      socket.setTimeout(4500);
      socket.on('timeout', () => {
        request.abort();
      });
    });
 
    // handle connection errors of the request
    request.on('error', (err) => reject(err));
    request.write(JSON.stringify(bod));
    request.end();
  })
);