All files / src/protocols http.js

90.67% Statements 136/150
90% Branches 81/90
80.77% Functions 21/26
90.6% Lines 135/149

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 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352      7x 7x       50x   50x       50x   50x   50x   50x 2x   2x 2x   2x       2x                           27x       12x                       2x             9x       9x   8x 5x   5x     3x 1x 1x 1x     1x   1x 2x     2x   2x 1x 1x   1x     1x       1x 1x 1x 1x     1x             8x     8x     1x 1x   1x 1x                       10x                       10x   10x 45x   45x 1x   44x 1x   43x 1x   42x 33x   9x 7x       10x     10x   1x 1x   1x       9x 9x     9x 9x   9x 1x 1x 1x       9x 9x 6x   6x 3x     5x         2x 1x       3x       9x 3x     9x 9x         12x     6x   6x 1x   6x   6x 6x   6x         5x       6x   6x 6x   6x   6x 1x 1x       6x   6x 1x     6x 1x 1x 1x             6x         8x 8x   8x   8x 17x   17x 8x 9x 2x       8x     8x 3x     8x                     2x   2x 2x   2x 4x 1x     4x         4x 3x       2x   1x         1x     7x  
'use strict';
 
const
  staticHttpRoutes = require('./routes.json'),
  KuzzleAbstractProtocol = require('./abstract/common');
 
class HttpWrapper extends KuzzleAbstractProtocol {
  constructor(host, options = {}) {
    super(host, options);
 
    Iif (typeof host !== 'string' || host === '') {
      throw new Error('host is required');
    }
 
    this._routes = {};
 
    this._timeout = options.timeout || 0;
 
    this.customRoutes = options.customRoutes || {};
 
    for (const controller of Object.keys(this.customRoutes)) {
      const definition = this.customRoutes[controller];
 
      for (const action of Object.keys(definition)) {
        const route = definition[action];
 
        Iif (!(typeof route.url === 'string' && route.url.length > 0)) {
          throw new Error(
            `Incorrect URL for custom route ${controller}:${action}.`);
        }
        Iif (!(typeof route.verb === 'string' && route.verb.length > 0)) {
          throw new Error(
            `Incorrect VERB for custom route ${controller}:${action}.`);
        }
      }
    }
  }
 
  // @deprecated
  get http () {
    return this.routes;
  }
 
  get routes () {
    return this._routes;
  }
 
  get protocol () {
    return this.ssl ? 'https' : 'http';
  }
 
  get connected () {
    return true;
  }
 
  get timeout () {
    return this._timeout;
  }
 
  set timeout (timeout) {
    this._timeout = timeout;
  }
 
  /**
   * Connect to the server
   */
  connect () {
    Iif (this.state === 'ready') {
      return Promise.resolve();
    }
 
    return this._sendHttpRequest('GET', '/_publicApi')
      .then(({ result, error }) => {
        if (! error) {
          this._routes = this._constructRoutes(result);
 
          return;
        }
 
        if (error.status === 401 || error.status === 403) {
          this._warn('"server:publicApi" route is restricted for anonymous user.');
          this._warn('This route is used by the HTTP protocol to build API URLs.');
          this._warn('Fallback to static routes, some API routes may be unavailable as well as plugin custom routes');
 
          // fallback to static http routes
          this._routes = staticHttpRoutes;
 
          return;
        } else Eif (error.status === 404) {
          // fallback to server:info route
          // server:publicApi is only available since Kuzzle 1.9.0
          return this._sendHttpRequest('GET', '/')
            .then(({ result: res, error: err }) => {
              if (! err) {
                this._routes = this._constructRoutes(res.serverInfo.kuzzle.api.routes);
                this._staticRoutes = false;
 
                return;
              }
 
              Iif (err.status !== 401 && err.status !== 403) {
                throw err;
              }
 
              this._warn('"server:info" route is restricted for anonymous user.');
              this._warn('This route is used by the HTTP protocol to build API URLs.');
              this._warn('If you want to expose your API routes without disclosing server information you can use "server:publicApi" (available in Kuzzle 1.9.0).');
              this._warn('Fallback to static routes, some API routes may be unavailable as well as plugin custom routes');
 
              // fallback to static http routes
              this._routes = staticHttpRoutes;
            });
        }
 
        throw error;
      })
      .then(() => {
        this._routes = Object.assign(this._routes, this.customRoutes);
 
        // 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 (Object.prototype.hasOwnProperty.call(payload, key)) {
        payload[key] = value;
      }
      else if (value !== undefined && value !== null) {
        queryArgs[key] = value;
      }
    }
 
    const route = this.routes[payload.controller]
        && this.routes[payload.controller][payload.action];
 
    if (! route) {
      const error =
        new Error(`No URL found for "${payload.controller}:${payload.action}".`);
      this.emit(payload.requestId, {status: 400, error});
 
      return;
    }
 
    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];
 
      if (Array.isArray(value)) {
        queryString.push(...value.map(v => `${key}=${v}`));
 
      }
      else if (typeof value === 'boolean') {
        // In Kuzzle, an optional boolean option is set to true if present in
        // the querystring, and false if absent.
        // As there is no boolean type in querystrings, encoding a boolean
        // option "foo=false" in it will make Kuzzle consider it as truthy.
        if (value === true) {
          queryString.push(key);
        }
      }
      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');
 
      if (path[0] !== '/') {
        path = `/${path}`;
      }
      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,
        timeout: this._timeout
      })
        .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.timeout = this._timeout;
 
      xhr.onreadystatechange = () => {
        Eif (xhr.readyState === 4 && xhr.status === 0) {
          reject(new Error('Cannot connect to host. Is the host online?'));
        }
      };
 
      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);
    });
  }
 
  _constructRoutes (publicApi) {
    const apiRoutes = Object.keys(publicApi)
      .map(key => [key, publicApi[key]])
      .reduce((routes, [controller, definition]) => {
        routes[controller] = {};
 
        for (const action of Object.keys(definition)) {
          const { http } = definition[action];
 
          if (http && http.length === 1) {
            routes[controller][action] = http[0];
          } else if (http && http.length > 1) {
            routes[controller][action] = getCorrectRoute(http);
          }
        }
 
        return routes;
      }, {});
 
    for (const controller of Object.keys(this.customRoutes)) {
      apiRoutes[controller] = this.customRoutes[controller];
    }
 
    return apiRoutes;
  }
 
  _warn (message) {
    console.warn(message); // eslint-disable-line no-console
  }
 
}
 
function getCorrectRoute (routes) {
  let
    shortestRoute = routes[0],
    postRoute,
    minLength = routes[0].url.length,
    sameLength = true;
 
  for (const route of routes) {
    if (route.url.length !== minLength) {
      sameLength = false;
    }
 
    Iif (route.url.length < minLength) {
      shortestRoute = route;
      minLength = route.url.length;
    }
 
    if (route.verb === 'POST') {
      postRoute = route;
    }
  }
 
  if (sameLength) {
    // with same URL size, we keep the POST route
    return postRoute;
  }
 
  // with differents URL sizes, we keep the shortest because URL params
  // will be in the query string
  return shortestRoute;
}
 
module.exports = HttpWrapper;