Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. import buildQueryString from '~/utils/buildQueryString'
  2.  
  3. const FETCH_TIMEOUT = 10000
  4.  
  5. export const buildUrl = ({ path, params }) =>
  6. `//${process.env.API_BASE_URL}/${path}${buildQueryString(params)}`
  7.  
  8. export const fetchWithTimeout = (url, options) => Promise.race([
  9. new Promise((resolve, reject) => {
  10. setTimeout(() => {
  11. const e = new Error('Fetch request timeout! Server not responding at this url')
  12. e.name = 'Fetch Timeout error'
  13. e.type = 'TIMEOUT'
  14. reject(e)
  15. }, FETCH_TIMEOUT)
  16. }),
  17. fetch(url, options),
  18. ])
  19.  
  20. const apiFetch = async ({ params, path, options } = {}) => {
  21. const url = buildUrl({
  22. path,
  23. params,
  24. })
  25. try {
  26. const response = await fetchWithTimeout(url, options)
  27.  
  28. const json = response.status !== 204 && await response.json()
  29.  
  30. return {
  31. ok: response.ok,
  32. status: response.status,
  33. ...json,
  34. }
  35. } catch (e) {
  36. console.error(e.name)
  37. console.error(e.message)
  38. console.error(e.stack)
  39.  
  40. const status = e.type === 'TIMEOUT'
  41. ? 408
  42. : 500
  43.  
  44. return {
  45. ok: false,
  46. status,
  47. message: `${e.name}: ${e.message}`,
  48. error: e,
  49. }
  50. }
  51. }
  52.  
  53. export default apiFetch
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement