| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- const { jwt } = require('./security')
- const wrap = (fetch, options) => {
- const fn = async (url, body) => {
- try {
- const headers = {
- 'Accepts': 'application/json'
- }
- if (body) headers['Content-Type'] = 'application/json'
- const result = await fetch(url, {
- ...options,
- headers: {
- ...headers,
- ...(options && options.headers),
- ...(jwt.token && {
- 'Authorization': `Bearer ${jwt.token}`
- })
- },
- body: body && JSON.stringify(body)
- })
- const text = await result.text()
- try {
- return JSON.parse(text)
- } catch (err) {
- return {error: text}
- }
- } catch (error) {
- return {error}
- }
- }
- Object.defineProperties(fn, {
- get: { get: () => wrap(fetch, { ...options, method: 'GET' }) },
- post: { get: () => wrap(fetch, { ...options, method: 'POST' }) },
- put: { get: () => wrap(fetch, { ...options, method: 'PUT' }) },
- patch: { get: () => wrap(fetch, { ...options, method: 'PATCH' }) },
- delete: { get: () => wrap(fetch, { ...options, method: 'DELETE' }) }
- })
- return fn
- }
- const api = wrap(fetch)
- module.exports = api
|