Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import buildQueryString from '~/utils/buildQueryString'
- const FETCH_TIMEOUT = 10000
- export const buildUrl = ({ path, params }) =>
- `//${process.env.API_BASE_URL}/${path}${buildQueryString(params)}`
- export const fetchWithTimeout = (url, options) => Promise.race([
- new Promise((resolve, reject) => {
- setTimeout(() => {
- const e = new Error('Fetch request timeout! Server not responding at this url')
- e.name = 'Fetch Timeout error'
- e.type = 'TIMEOUT'
- reject(e)
- }, FETCH_TIMEOUT)
- }),
- fetch(url, options),
- ])
- const apiFetch = async ({ params, path, options } = {}) => {
- const url = buildUrl({
- path,
- params,
- })
- try {
- const response = await fetchWithTimeout(url, options)
- const json = response.status !== 204 && await response.json()
- return {
- ok: response.ok,
- status: response.status,
- ...json,
- }
- } catch (e) {
- console.error(e.name)
- console.error(e.message)
- console.error(e.stack)
- const status = e.type === 'TIMEOUT'
- ? 408
- : 500
- return {
- ok: false,
- status,
- message: `${e.name}: ${e.message}`,
- error: e,
- }
- }
- }
- export default apiFetch
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement