api.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const { jwt } = require('./security')
  2. const wrap = (fetch, options) => {
  3. const fn = async (url, body) => {
  4. try {
  5. const headers = {
  6. 'Accepts': 'application/json'
  7. }
  8. if (body) headers['Content-Type'] = 'application/json'
  9. const result = await fetch(url, {
  10. ...options,
  11. headers: {
  12. ...headers,
  13. ...(options && options.headers),
  14. ...(jwt.token && {
  15. 'Authorization': `Bearer ${jwt.token}`
  16. })
  17. },
  18. body: body && JSON.stringify(body)
  19. })
  20. const text = await result.text()
  21. try {
  22. return JSON.parse(text)
  23. } catch (err) {
  24. return {error: text}
  25. }
  26. } catch (error) {
  27. return {error}
  28. }
  29. }
  30. Object.defineProperties(fn, {
  31. get: { get: () => wrap(fetch, { ...options, method: 'GET' }) },
  32. post: { get: () => wrap(fetch, { ...options, method: 'POST' }) },
  33. put: { get: () => wrap(fetch, { ...options, method: 'PUT' }) },
  34. patch: { get: () => wrap(fetch, { ...options, method: 'PATCH' }) },
  35. delete: { get: () => wrap(fetch, { ...options, method: 'DELETE' }) }
  36. })
  37. return fn
  38. }
  39. const api = wrap(fetch)
  40. module.exports = api