Skip to content

Instantly share code, notes, and snippets.

@monzou
Created November 5, 2016 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monzou/6c6d2978978b7ec00004858a78195c3f to your computer and use it in GitHub Desktop.
Save monzou/6c6d2978978b7ec00004858a78195c3f to your computer and use it in GitHub Desktop.
Fetch API wrapper
const existy = value => value !== null && value !== undefined
export function resolve (host, relative, params) {
const path = `${host}/${relative}`
if (params) {
return `${path}?${toQueryParams(params)}`
}
return path
}
export function toQueryParams (params) {
return params ? Object.keys(params).filter(key => existy(params[key])).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`).join('&') : ''
}
import { resolve } from '../utils/path'
const TIMEOUT_MSEC = 10000
const timeout = (msec, promise) => {
return new Promise((resolve, reject) => {
const tid = setTimeout(() => {
reject(new Error(`Request has been timed out (${msec} msec)`))
}, msec)
promise.then(
response => {
clearTimeout(tid)
resolve(response)
},
error => {
clearTimeout(tid)
reject(error)
}
)
})
}
const wrap = fetch => {
return new Promise((resolve, reject) => {
fetch.then(response => {
if (response.ok) {
resolve(response.json())
} else {
reject(response)
}
})
})
}
export function request (method, host, relative, params) {
const path = resolve(host, relative, method === 'GET' ? params : null)
const options = {
method,
cache: 'no-cache',
mode: 'cors',
credentials: 'include'
}
switch (method) {
case 'POST':
case 'PUT':
case 'PATCH':
case 'DELETE':
options.headers = new Headers({ 'Content-Type': 'application/json' })
options.body = params ? JSON.stringify(params) : '{}'
break
default:
break
}
return timeout(TIMEOUT_MSEC, wrap(fetch(path, options)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment