(path = '/', method = 'GET', body = {})
| 1 | export default async function fetchAPI(path = '/', method = 'GET', body = {}) { |
| 2 | const API = '/api' |
| 3 | let err |
| 4 | let ops: Record<string, any> = { |
| 5 | headers: { |
| 6 | Accept: 'application/json', |
| 7 | 'Content-Type': 'application/json; charset=utf-8', |
| 8 | }, |
| 9 | method, |
| 10 | } |
| 11 | |
| 12 | if ((body && method === 'POST') || method === 'PATCH') { |
| 13 | ops.body = JSON.stringify(body) |
| 14 | } |
| 15 | |
| 16 | try { |
| 17 | const res = await fetch(`${API}${path}`, ops) |
| 18 | const data = await res.json() |
| 19 | return data |
| 20 | } catch (e: any) { |
| 21 | if (e.message === 'cancelled') { |
| 22 | // Cancelled by browser |
| 23 | console.log('Request Cancelled by the Browser ', e) |
| 24 | err = e |
| 25 | } else { |
| 26 | // Network error, CORS or timeout |
| 27 | console.error('Network Error, CORS or timeout.') |
| 28 | // err = isServer ? e : new Error(NETWORK_ERR_MESSAGE); |
| 29 | // err.code = NETWORK_ERR_CODE; |
| 30 | // err.status = e ? e.status : null; |
| 31 | } |
| 32 | } |
| 33 | } |
no test coverage detected