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 | 19x 18x 18x 18x 4x 18x 18x 19x 18x 18x 18x 18x 5x 18x 19x 51x 51x 51x 51x 51x 15x 15x 15x 51x 18x 18x 18x 18x 13x 13x 13x 10x 13x 5x 18x | import fetchWrapper from './fetchWrapper'
import includes from 'lodash/includes'
import makeRequestKey from './makeRequestKey'
import microTask from '@r14c/async-utils/microTask'
import omitNil from './omitNil'
import stringify from 'json-stable-stringify'
import toQueryString from './toQueryString'
const normalizeHeaders = (options) => {
let headers = {...options.headers}
Iif (!options.method) {
throw new Error('options.method must be defined')
}
if (includes(['PUT', 'POST'], options.method.toUpperCase())) {
headers['Content-Type'] = 'application/json'
}
headers['Accept'] = 'application/json'
return headers
}
const getUrl = (options) => {
let url = options.url
const params = omitNil(options.params || {})
const qs = toQueryString(params)
if (qs) {
url += `?${qs}`
}
return url
}
const createHttpAdapter = (options = {}) => {
let promiseCache = {}
const adapter = options.adapter || fetchWrapper
const deserialize = options.deserialize || ((response, data) => data)
const cacheTimeout = options.cacheTimeout || 500 // evict promise cache keys after 500ms by default
const createRequest = (url, request) => {
return adapter(url, request)
.then((response) => {
return response.json()
.then((data) => microTask(() => deserialize(response, data)))
})
}
return (options = {}) => {
let promise
const force = options.force || false
const url = getUrl(options)
const request = {
...options,
headers: normalizeHeaders(options),
body: (options.body) ? stringify(options.body) : undefined
}
if (options.method === 'GET') {
const key = makeRequestKey(url, request)
promise = promiseCache[key]
if (!promise || force === true) {
promise = promiseCache[key] = createRequest(url, request)
}
setTimeout(() => {
delete promiseCache[key]
}, cacheTimeout)
} else {
promise = createRequest(url, request)
}
return promise
}
}
export default createHttpAdapter
|