Skip to content

Instantly share code, notes, and snippets.

@monzou monzou/path.js
Created Nov 5, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.