All files http-fetch.js

0% Statements 0/51
0% Branches 0/18
0% Functions 0/16
0% Lines 0/50

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                                                                                                                                                                                                                     
import Observable from './observable.js'
export default class HttpFetch extends Observable {
 
  constructor(requestHeaders = {}) {
    super()
    this.requestHeaders = requestHeaders
  }
 
  async _httpFetch(url, body, verb) {
    const myHeaders = new Headers()
 
    if (typeof this.requestHeaders === 'object') {
      Object.entries(this.requestHeaders).forEach(([key, value]) => {
        myHeaders.set(key, value)
      })
    }
 
    let myInit = { cache: 'default', method: verb, mode: 'cors' }
    myInit.body = body
    if (body && !(body instanceof FormData)) {
      myInit.body = JSON.stringify(body)
      myHeaders.set('Content-Type', 'application/json')
    }
    myInit.headers = myHeaders
 
    try {
      const response = await fetch(url, myInit)
      const responseText = await response.clone().text()
      const json = responseText.length ? JSON.parse(responseText) : {}
      if (response.ok) {
        this.notify(json)
      } else {
        this.notifyError(response)
      }
    } catch (error) {
      this.notifyError(error)
    }
  }
 
  static addParamsToURL(url, params = {}) {
    let result = url
    try {
      const pathURL = new URL(url)
      const searchParams = pathURL.searchParams
      Object.entries(params)
        .map(param => param.map(window.encodeURIComponent))
        .forEach(([key, value]) => {
          if (!searchParams.has(key)) {
            searchParams.append(key, value)
          }
        })
      result = `${pathURL.origin}${pathURL.pathname}?${searchParams.toString()}`
    } catch (error) {
      result = url
    }
    return result
  }
 
  generateUrlParams(params = {}) {
    return `?${Object.entries(params).map(param => param.map(window.encodeURIComponent).join('=')).join('&')}`
  }
 
  get(url, params = null) {
    if (params) {
      url = this.constructor.addParamsToURL(url, params)
    }
    return {
      subscribe: f => {
        const unsubscribe = this.subscribe.call(this, f)
        this._httpFetch(url, null, 'GET')
        return unsubscribe
      }
    }
  }
 
  post(url, body) {
    return {
      subscribe: f => {
        const unsubscribe = this.subscribe.call(this, f)
        this._httpFetch(url, body, 'POST')
        return unsubscribe
      }
    }
  }
 
  put(url, body) {
    return {
      subscribe: f => {
        const unsubscribe = this.subscribe.call(this, f)
        this._httpFetch(url, body, 'PUT')
        return unsubscribe
      }
    }
  }
 
  delete(url) {
    return {
      subscribe: f => {
        const unsubscribe = this.subscribe.call(this, f)
        this._httpFetch(url, null, 'DELETE')
        return unsubscribe
      }
    }
  }
 
}