Created
November 5, 2016 13:10
-
-
Save monzou/6c6d2978978b7ec00004858a78195c3f to your computer and use it in GitHub Desktop.
Fetch API wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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('&') : '' | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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