All files / api Api.js

93.18% Statements 82/88
89.29% Branches 50/56
100% Functions 20/20
93.18% Lines 82/88

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                    9x                       17x   17x 17x   17x                       3x                   6x   6x 10x 4x 4x     6x     6x 4x                 3x               4x 1x     3x               3x 1x     2x             2x             2x                   9x 2x     7x 1x     6x       6x 1x     5x                               1x         1x       1x 2x         20x           32x 32x   32x 32x       1x     32x 1x     32x   31x   31x 4x         4x   4x     31x 31x   1x 1x           32x   32x       33x 1x     32x       32x     2x     32x 32x 31x   31x     1x                         26x   26x               26x       26x 26x 26x 22x   4x       26x   26x             4x     26x         19x       2x       1x       1x       6x          
import { ApiError } from '../errors/ApiError'
import { stringify } from 'qs'
import { isAbsoluteUri, validateCallbackFn } from '../shared/utils'
 
/**
 * Some headers cannot be reconfigured to stop users from
 * accidental errors.
 *
 * @type {string[]}
 */
const READ_ONLY_HEADERS = [
  'Accept',
  'Content-type'
]
 
/**
 * Wrapper around json:api 1.0 requests, sets content type and other defaults.
 *
 * @class Api
 */
export class Api {
  constructor () {
    this.baseUrl = ''
 
    this.successCallbacks = []
    this.errorCallbacks = []
 
    this.headers = {
      Accept: 'application/vnd.api+json',
      'Content-Type': 'application/vnd.api+json'
    }
  }
 
  /**
   * Functions to be called after successful requests.
   *
   * @param {Function[]} callbacks
   */
  setSuccessCallbacks (callbacks) {
    this._setCallbacks('successCallbacks', callbacks)
  }
 
  /**
   *
   * @param {string} property
   * @param {Function[]} callbacks
   * @private
   */
  _setCallbacks (property, callbacks) {
    const errored = []
 
    for (const i in callbacks) {
      if (!validateCallbackFn(callbacks[i])) {
        errored.push(i)
        continue
      }
 
      this[property].push(callbacks[i])
    }
 
    if (errored.length) {
      throw new ApiError('Invalid callbacks: ' + callbacks.join(', '))
    }
  }
 
  /**
   *
   * @param {Function[]} callbacks
   */
  setErrorCallbacks (callbacks) {
    this._setCallbacks('errorCallbacks', callbacks)
  }
 
  /**
   *
   * @param {Function} callback
   */
  addSuccessCallback (callback) {
    if (!validateCallbackFn(callback)) {
      throw new ApiError('You must pass a valid callback to this method')
    }
 
    this.successCallbacks.push(callback)
  }
 
  /**
   *
   * @param {Function} callback
   */
  addErrorCallback (callback) {
    if (!validateCallbackFn(callback)) {
      throw new ApiError('You must pass a valid callback to this method')
    }
 
    this.errorCallbacks.push(callback)
  }
 
  /**
   * Reset the response success handling to the default behaviour
   */
  resetSuccessCallbacks () {
    this.successCallbacks = []
  }
 
  /**
   * Reset the response error to the default behaviour
   */
  resetErrorCallbacks () {
    this.errorCallbacks = []
  }
 
  /**
   *
   * @param {string} name
   * @param {string} value
   * @param {boolean} overwrite
   */
  setHeader (name, value, overwrite = false) {
    if (typeof name !== 'string') {
      throw new ApiError('Expected name to be string, got ' + typeof name)
    }
 
    if (READ_ONLY_HEADERS.includes(name)) {
      throw new ApiError('Cannot change default headers')
    }
 
    Iif (typeof value !== 'string') {
      throw new ApiError('Expected value to be string, got ' + typeof value)
    }
 
    if (Object.keys(this.headers).includes(name) && !overwrite) {
      throw new ApiError('Header is already set, not overwriting.')
    }
 
    this.headers[name] = value
  }
 
  /**
   * Add multiple request headers at once by passing an object:
   *
   * ```js
   * api.addHeaders({
   *   'X-My-Header': 'my-header-value',
   *   'E-Tag': '12923-434-123'
   * })
   * ```
   *
   * @param {Object} headers
   */
  addHeaders (headers) {
    Iif (headers.constructor !== Object) {
      throw new Error('You must pass an object to this method')
    }
 
    // make sure there is a spreadable object in headers
    Iif (!headers || Object.getOwnPropertyNames(headers).length < 1) {
      headers = {}
    }
 
    for (const [name, value] of Object.entries(headers)) {
      this.setHeader(name, value)
    }
  }
 
  setBaseUrl (baseUrl) {
    this.baseUrl = baseUrl
  }
 
  /* #region request methods */
 
  _compileUrl (url, params) {
    let urlObj = null
    let baseUrlObj = null
 
    try {
      baseUrlObj = new URL(this.baseUrl)
    } catch (e) {
      // if the base url cannot be constructed it is most likely due
      // to it being a relative path assumed to work based off of window.location.href
      baseUrlObj = new URL(this.baseUrl, window.location.href)
    }
 
    if (url.indexOf('//') === 0) {
      url = baseUrlObj.protocol + url
    }
 
    if (!isAbsoluteUri(url)) {
      // various path adjustments
      url = url.replace(/^(\/)(.+)/, '$2')
 
      if (baseUrlObj.pathname !== '' && baseUrlObj.pathname !== '/') {
        const deSlashedBaseUrlPath = baseUrlObj.pathname.replace(
          /(\/)(.+)(\/)$/,
          '$2'
        )
 
        url = deSlashedBaseUrlPath + '/' + url
 
        baseUrlObj.pathname = ''
      }
 
      urlObj = new URL(baseUrlObj.href)
      urlObj.pathname = url
    } else {
      try {
        urlObj = new URL(url)
      } catch (e) {
        throw new ApiError('Invalid url: ' + url)
      }
    }
 
    urlObj.search = stringify(params, { encodeValuesOnly: true, arrayFormat: 'brackets' })
 
    return urlObj.href
  }
 
  isUrlCrossDomain (url) {
    if (typeof url !== 'string') {
      return false
    }
 
    Iif (url.length === 0) {
      return false
    }
 
    if (url.indexOf('//') === 0) {
      // this is only valid in here as the url is not actually used this way!
      // please check _compileUrl for the correct way to do this
      url = 'http:' + url
    }
 
    try {
      const urlObj = new URL(url)
      const baseUrlObj = new URL(this.baseUrl)
 
      return urlObj.host !== baseUrlObj.host
    } catch (e) {}
 
    return url.length > 0 && isAbsoluteUri(url)
  }
 
  /**
   *
   * @param {string} method
   * @param {string} url
   * @param {Object} params
   * @param {Object} data
   * @returns {Promise<Response>}
   * @protected
   */
  async _doRequest (method, url, params, data) {
    url = this._compileUrl(url, params)
 
    const requestConfig = {
      body: null,
      headers: this.headers,
      method: method.toUpperCase(),
      mode: this.isUrlCrossDomain(url) ? 'cors' : 'same-origin',
      referrerPolicy: 'strict-origin-when-cross-origin'
    }
 
    Iif (data) {
      requestConfig.body = JSON.stringify(data)
    }
 
    return fetch(url, requestConfig).then(async response => {
      let callbacks = []
      if (response.ok) {
        callbacks = this.successCallbacks
      } else {
        callbacks = this.errorCallbacks
      }
 
      // prevent any modification of the response data
      Object.seal(response)
 
      for (const callback of callbacks) {
        // note: this does not quite work as the response body
        //       cannot be modified or even read twice.
        //       the current solution of cloning the response
        //       to every callback, may incur performance
        //       pressure as typical callbacks likely want to examine the
        //       request body and would repeatedly parse the json bodies
        await callback(response.clone())
      }
 
      return response
    })
  }
 
  get (url, params = null) {
    return this._doRequest('get', url, params, null)
  }
 
  post (url, params = null, data = null) {
    return this._doRequest('post', url, params, data)
  }
 
  put (url, params = null, data = null) {
    return this._doRequest('put', url, params, data)
  }
 
  patch (url, params = null, data = null) {
    return this._doRequest('patch', url, params, data)
  }
 
  delete (url, params = null, data = null) {
    return this._doRequest('delete', url, params, data)
  }
 
  /* #endregion */
}