api.js 867 B

1234567891011121314151617181920212223242526272829
  1. const wrap = (fetch, options) => {
  2. const fn = async (url, body) => {
  3. const headers = {
  4. 'Accepts': 'application/json'
  5. }
  6. if (body) headers['Content-Type'] = 'application/json'
  7. const result = await fetch(url, {
  8. ...options,
  9. headers: {
  10. ...headers,
  11. ...(options && options.headers)
  12. },
  13. body: body && JSON.stringify(body)
  14. })
  15. return await result.json()
  16. }
  17. Object.defineProperties(fn, {
  18. get: { get: () => wrap(fetch, { ...options, method: 'GET' }) },
  19. post: { get: () => wrap(fetch, { ...options, method: 'POST' }) },
  20. put: { get: () => wrap(fetch, { ...options, method: 'PUT' }) },
  21. patch: { get: () => wrap(fetch, { ...options, method: 'PATCH' }) },
  22. delete: { get: () => wrap(fetch, { ...options, method: 'DELETE' }) }
  23. })
  24. return fn
  25. }
  26. const api = wrap(fetch)
  27. module.exports = api