All files / src/networkWrapper/protocols http.js

87.21% Statements 75/86
87.27% Branches 48/55
78.57% Functions 11/14
88.24% Lines 75/85

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249      6x     6x                                                                                 37x   37x         37x 1x 2x 2x             54x       9x             5x 1x     5x       5x       5x 5x 10x 1x     10x 10x                   5x                                     8x                       8x   8x 34x   34x 1x   33x 1x   32x 1x   31x 27x   4x 2x         8x   8x 1x 1x       8x 7x     7x 7x   7x 1x 1x 1x       7x 7x 1x   1x         1x       7x 1x     7x 7x         9x     5x 5x   5x 5x   5x       4x       4x   4x 4x   4x   4x 1x     4x 1x 1x 1x             4x           6x  
'use strict';
 
const
  AbtractWrapper = require('./abstract/common');
 
const
  _routes = {
    routes: {
      auth: {
        login: {
          verb: 'POST',
          url: '/_login/:strategy'
        }
      },
      bulk: {
        import: {
          verb: 'POST',
          url: '/:index/:collection/_bulk'
        }
      },
      document: {
        create: {
          verb: 'POST',
          url: '/:index/:collection/_create'
        }
      },
      security: {
        createFirstAdmin: {
          verb: 'POST',
          url: '/_createFirstAdmin'
        },
        createRestrictedUser: {
          verb: 'POST',
          url: '/users/_createRestricted'
        },
        createUser: {
          verb: 'POST',
          url: '/users/_create'
        }
      }
    }
  };
 
 
class HttpWrapper extends AbtractWrapper {
 
  constructor(options = {}) {
    super(options);
 
    Iif (typeof this.host !== 'string' || this.host === '') {
      throw new Error('options.host is required');
    }
 
    // Application-side HTTP route overrides:
    if (options.http && options.http.customRoutes) {
      for (const controller in options.http.customRoutes) {
        Eif (options.http.customRoutes.hasOwnProperty(controller)) {
          this.http.routes[controller] = Object.assign(this.http.routes[controller] || {}, options.http.customRoutes[controller]);
        }
      }
    }
  }
 
  get http () {
    return _routes;
  }
 
  get protocol () {
    return this.ssl ? 'https' : 'http';
  }
 
  /**
   * Connect to the websocket server
   */
  connect () {
    if (this.autoQueue) {
      this.startQueuing();
    }
 
    Iif (this.state === 'ready') {
      return Promise.resolve();
    }
 
    return this._sendHttpRequest('GET', '/')
      .then(res => {
        // Get HTTP Routes from Kuzzle serverInfo
        // (if more than 1 available route for a given action, get the first one):
        const routes = res.result.serverInfo.kuzzle.api.routes;
        for (const controller of Object.keys(routes)) {
          if (this.http.routes[controller] === undefined) {
            this.http.routes[controller] = {};
          }
 
          for (const action of Object.keys(routes[controller])) {
            Iif (this.http.routes[controller][action] === undefined
              && Array.isArray(routes[controller][action].http)
              && routes[controller][action].http.length > 0) {
 
              this.http.routes[controller][action] = routes[controller][action].http[0];
            }
          }
        }
 
        // Client is ready
        this.clientConnected();
      })
      .catch(err => {
        const connectionError = new Error(`Unable to connect to kuzzle server at ${this.host}:${this.port}`);
        connectionError.internal = err;
 
        this.emit('networkError', connectionError);
        throw err;
      });
  }
 
  /**
   * Sends a payload to the connected server
   *
   * @param {Object} data
   * @returns {Promise<any>}
   */
  send (data) {
    const
      payload = {
        action: undefined,
        body: undefined,
        collection: undefined,
        controller: undefined,
        headers: {
          'Content-Type': 'application/json'
        },
        index: undefined,
        meta: undefined,
        requestId: undefined,
      },
      queryArgs = {};
 
    for (const key of Object.keys(data)) {
      const value = data[key];
 
      if (key === 'body') {
        payload.body = JSON.stringify(value);
      }
      else if (key === 'jwt') {
        payload.headers.authorization = 'Bearer ' + value;
      }
      else if (key === 'volatile') {
        payload.headers['x-kuzzle-volatile'] = JSON.stringify(value);
      }
      else if (payload.hasOwnProperty(key)) {
        payload[key] = value;
      }
      else if (value !== undefined && value !== null) {
        queryArgs[key] = value;
      }
    }
 
    const
      route = this.http.routes[payload.controller] && this.http.routes[payload.controller][payload.action];
 
    if (route === undefined) {
      const error = new Error(`No route found for ${payload.controller}/${payload.action}`);
      this.emit(payload.requestId, {status: 400, error});
    }
 
    const
      method = route.verb,
      regex = /\/:([^/]*)/;
 
    let
      url = route.url,
      matches = regex.exec(url);
 
    while (matches) {
      url = url.replace(regex, '/' + data[ matches[1] ]);
      delete(queryArgs[ matches[1] ]);
      matches = regex.exec(url);
    }
 
    // inject queryString arguments:
    const queryString = [];
    for (const key of Object.keys(queryArgs)) {
      const value = queryArgs[key];
 
      Iif (Array.isArray(value)) {
        queryString.push(...value.map(v => `${key}=${v}`));
 
      }
      else {
        queryString.push(`${key}=${value}`);
      }
    }
 
    if (queryString.length > 0) {
      url += '?' + queryString.join('&');
    }
 
    this._sendHttpRequest(method, url, payload)
      .then(response => this.emit(payload.requestId, response))
      .catch(error => this.emit(payload.requestId, {error}));
  }
 
  _sendHttpRequest (method, path, payload = {}) {
    if (typeof XMLHttpRequest === 'undefined') {
      // NodeJS implementation, using http.request:
 
      const httpClient = require('min-req-promise');
      const url = `${this.protocol}://${this.host}:${this.port}${path}`;
 
      const headers = payload.headers || {};
      headers['Content-Length'] = Buffer.byteLength(payload.body || '');
 
      return httpClient.request(url, method, {
        headers,
        body: payload.body
      })
        .then(response => JSON.parse(response.body));
    }
 
    // Browser implementation, using XMLHttpRequest:
    return new Promise((resolve, reject) => {
      const
        xhr = new XMLHttpRequest(),
        url = `${this.protocol}://${this.host}:${this.port}${path}`;
 
      xhr.open(method, url);
 
      for (const header of Object.keys(payload.headers || {})) {
        xhr.setRequestHeader(header, payload.headers[header]);
      }
 
      xhr.onload = () => {
        try {
          const json = JSON.parse(xhr.responseText);
          resolve(json);
        }
        catch (err) {
          reject(err);
        }
      };
 
      xhr.send(payload.body);
    });
  }
 
}
 
module.exports = HttpWrapper;