All files / src/rest BrowserHTTP.ts

8.08% Statements 8/99
0% Branches 0/22
0% Functions 0/19
8.16% Lines 8/98

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 3111x   1x       1x       1x   1x 1x   1x               1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
import axios from 'axios';
import { AxiosStatic, AxiosInstance, /*AxiosResponse,*/ AxiosRequestConfig } from 'axios';
import * as clonedeep from 'lodash.clonedeep';
 
if (!fetch) { // eslint-disable-line
  // @ts-ignore
  var fetch = require('node-fetch');
}
 
/** @hidden */
const URI = require('urijs');
 
import { AbstractHTTP } from './AbstractHTTP';
import { TwitarrError } from '../api/TwitarrError';
import { TwitarrHTTPOptions } from '../api/TwitarrHTTPOptions';
import { TwitarrResult } from '../api/TwitarrResult';
import { TwitarrServer } from '../api/TwitarrServer';
 
/**
 * Implementation of the [[ITwitarrHTTP]] interface using Axios: https://github.com/mzabriskie/axios
 * @module AxiosHTTP
 * @implements ITwitarrHTTP
 */
export class BrowserHTTP extends AbstractHTTP {
  /**
   * The Axios implementation class we'll use for making ReST calls.  This is necessary
   * to make sure we end up with the correct backend (XMLHttpRequest or Node.js 'http')
   * at runtime.
   * @hidden
   */
  private axiosImpl: AxiosStatic;
 
  /**
   * The Axios instance we'll use for making ReST calls.  This will be reinitialized whenever
   * the server configuration changes.
   */
  private axiosObj: AxiosInstance;
 
  /**
   * Construct an AxiosHTTP instance.
   * @param server - The server to connect to.
   * @param axiosImpl - The Axios implementation class to use.
   * @param timeout - The default timeout for ReST connections.
   */
  public constructor(server?: TwitarrServer, axiosImpl?: AxiosStatic, timeout = 10000) {
    super(server, timeout);
    this.axiosImpl = axiosImpl || axios;
  }
 
  /**
   * Make an HTTP GET call using `axios.request({method:'get'})`.
   */
  public get(url: string, options?: TwitarrHTTPOptions) {
    const realUrl = this.getServer(options).resolveURL(url);
    const opts = this.getConfig(options);
 
    const urlObj = new URI(realUrl);
    urlObj.search(opts.params);
    console.debug('GET ' + urlObj.toString());
 
    opts.method = 'get';
    opts.url = realUrl;
 
    return this.getImpl(options)
      .request(opts)
      .then(response => {
        let type;
        if (response.headers && response.headers['content-type']) {
          type = response.headers['content-type'];
        }
        const data = this.getData(response);
        if (data && data.status === 'error') {
          throw response;
        }
        return TwitarrResult.ok(this.getData(response), undefined, response.status, type);
      })
      .catch(err => {
        throw this.handleError(err, opts);
      });
  }
 
  /**
   * Make an HTTP PUT call using `axios.request({method:'put'})`.
   */
  public put(url: string, options?: TwitarrHTTPOptions) {
    const realUrl = this.getServer(options).resolveURL(url);
    const opts = this.getConfig(options);
 
    const urlObj = new URI(realUrl);
    urlObj.search(opts.params);
    console.debug('PUT ' + urlObj.toString());
 
    opts.data = Object.apply({}, opts.params);
    opts.method = 'put';
    opts.url = realUrl;
 
    return this.getImpl(options)
      .request(opts)
      .then(response => {
        let type;
        if (response.headers && response.headers['content-type']) {
          type = response.headers['content-type'];
        }
        const data = this.getData(response);
        if (data && data.status === 'error') {
          throw response;
        }
        return TwitarrResult.ok(this.getData(response), undefined, response.status, type);
      })
      .catch(err => {
        throw this.handleError(err, opts);
      });
  }
 
  /**
   * Make an HTTP POST call using `axios.request({method:'post'})`.
   */
  public post(url: string, options?: TwitarrHTTPOptions) {
    const realUrl = this.getServer(options).resolveURL(url);
    const opts = this.getConfig(options);
 
    const urlObj = new URI(realUrl);
    urlObj.search(opts.params);
    console.debug('POST ' + urlObj.toString());
 
    opts.method = 'post';
    opts.url = realUrl;
 
    return this.getImpl(options)
      .request(opts)
      .then(response => {
        let type;
        if (response.headers && response.headers['content-type']) {
          type = response.headers['content-type'];
        }
        const data = this.getData(response);
        if (data && data.status === 'error') {
          throw response;
        }
        return TwitarrResult.ok(this.getData(response), undefined, response.status, type);
      })
      .catch(err => {
        throw this.handleError(err, opts);
      });
  }
 
  /**
   * Make an HTTP DELETE call using `axios.request({method:'delete'})`.
   */
  public httpDelete(url: string, options?: TwitarrHTTPOptions) {
    const realUrl = this.getServer(options).resolveURL(url);
    const opts = this.getConfig(options);
 
    const urlObj = new URI(realUrl);
    urlObj.search(opts.params);
    console.debug('DELETE ' + urlObj.toString());
 
    opts.method = 'delete';
    opts.url = realUrl;
 
    return this.getImpl(options)
      .request(opts)
      .then(response => {
        let type;
        if (response.headers && response.headers['content-type']) {
          type = response.headers['content-type'];
        }
        const data = this.getData(response);
        if (data && data.status === 'error') {
          throw response;
        }
        return TwitarrResult.ok(this.getData(response), undefined, response.status, type);
      })
      .catch(err => {
        throw this.handleError(err, opts);
      });
  }
 
  /** POST a file. */
  public async postFile(url: string, fileName: string, contentType: string, data: Buffer, options?: TwitarrHTTPOptions): Promise<TwitarrResult<any>> {
    const opts = this.getOptions(options)
      .withHeader('content-type', 'multipart/form-data')
      .withParameter('key', this.getKey());
 
    const fetchObj = this.getFetchObject(fileName, contentType, data, opts);
    const u = URI(this.server.url).resource(this.server.resolveURL(url, opts.parameters));
 
    const fetchOpts = Object.assign(
      {
        cache: 'no-cache',
        credentials: 'same-origin',
        method: 'POST',
        mode: 'cors',
        redirect: 'follow',
      },
      fetchObj,
    );
 
    return fetch(u.toString(), fetchOpts).then(async response => {
      const json = await response.json();
      return TwitarrResult.ok(json, undefined, response.status, response.headers['content-type']);
    });
  }
 
  protected getFetchObject(fileName: string, contentType: string, data: Buffer, options: TwitarrHTTPOptions): any {
    const fd = new FormData();
    fd.append('name', fileName);
    fd.append('file', new Blob([data], { type: contentType }), fileName);
 
    return {
      body: fd,
      headers: options.headers,
    };
  }
 
  /**
   * Clear the current [[AxiosInstance]] so it is recreated on next request with the
   * new server configuration.
   */
  protected onSetServer() {
    super.onSetServer();
    this.axiosObj = undefined;
  }
 
  /**
   * Internal method to turn [[TwitarrHTTPOptions]] into an [[AxiosRequestConfig]] object.
   * @hidden
   */
  private getConfig(options?: TwitarrHTTPOptions): AxiosRequestConfig {
    const allOptions = this.getOptions(options);
 
    const ret: AxiosRequestConfig = {
      transformResponse: [], // we do this so we can post-process only on success
    };
 
    if (allOptions.auth && allOptions.auth.username && allOptions.auth.password) {
      ret.auth = {
        password: allOptions.auth.password,
        username: allOptions.auth.username,
      };
    }
 
    if (allOptions.timeout) {
      ret.timeout = allOptions.timeout;
    }
 
    if (allOptions.headers) {
      ret.headers = clonedeep(allOptions.headers);
    } else {
      ret.headers = {};
    }
 
    if (!ret.headers.accept) {
      ret.headers.accept = 'application/json';
    }
    if (!ret.headers['content-type']) {
      ret.headers['content-type'] = 'application/json;charset=utf-8';
    }
 
    const type = ret.headers.accept;
    ret.transformResponse = [];
    if (type === 'application/json') {
      ret.responseType = 'json';
    } else if (type === 'text/plain') {
      ret.responseType = 'text';
    } else {
      throw new TwitarrError('Unhandled "Accept" header: ' + type);
    }
 
    if (allOptions.parameters) {
      ret.params = clonedeep(allOptions.parameters);
    }
 
    if (allOptions.data) {
      ret.data = clonedeep(allOptions.data);
    }
 
    return ret;
  }
 
  /**
   * Internal method for getting/constructing an Axios object on-demand,
   * based on the current server configuration.
   * @hidden
   */
  private getImpl(options?: TwitarrHTTPOptions) {
    if (!this.axiosObj) {
      const server = this.getServer(options);
      if (!server) {
        throw new TwitarrError('You must set a server before attempting to make queries using Axios!');
      }
      const allOptions = this.getOptions(options);
 
      const axiosOpts: AxiosRequestConfig = {
        baseURL: server.url,
        timeout: allOptions.timeout,
        withCredentials: true,
      };
 
      if (typeof XMLHttpRequest !== 'undefined') {
        axiosOpts.adapter = require('axios/lib/adapters/xhr.js');
      } else if (typeof process !== 'undefined') {
        axiosOpts.adapter = require('axios/lib/adapters/http.js');
      }
 
      this.axiosObj = this.axiosImpl.create(axiosOpts);
    }
    return this.axiosObj;
  }
}