|
| 1 | +const fetchResult = async (url: RequestInfo, init?: RequestInit): Promise<any> => { |
| 2 | + const response = await fetch(url, { |
| 3 | + credentials: 'include', |
| 4 | + headers: { |
| 5 | + 'Content-type': 'application/json; charset=UTF-8', |
| 6 | + Accept: 'application/json', |
| 7 | + }, |
| 8 | + ...init, |
| 9 | + }); |
| 10 | + |
| 11 | + if (!response.ok) { |
| 12 | + throw new Error(`Could not fetch ${url}. Response NOT OK.`); |
| 13 | + } |
| 14 | + const json = await response.json(); |
| 15 | + if (json.errors) { |
| 16 | + throw new Error(`Could not fetch ${url}. Response contains errors.`); |
| 17 | + } |
| 18 | + return json; |
| 19 | +}; |
| 20 | + |
| 21 | +const jsonRequest = async <T>(input: RequestInfo, method: string, init?: RequestInit): Promise<T> => { |
| 22 | + return fetchResult(input, { |
| 23 | + method: method, |
| 24 | + ...init, |
| 25 | + }); |
| 26 | +}; |
| 27 | + |
| 28 | +export const getJson = async <T>(input: RequestInfo, init?: RequestInit): Promise<T> => jsonRequest(input, 'GET', init); |
| 29 | + |
| 30 | +export const postJson = async <T>(input: RequestInfo, body: any, init?: RequestInit): Promise<T> => |
| 31 | + jsonRequest(input, 'POST', { |
| 32 | + body: JSON.stringify(body), |
| 33 | + ...init, |
| 34 | + }); |
| 35 | + |
| 36 | +export const useFetchResult = () => { |
| 37 | + const abortController = new AbortController(); |
| 38 | + const abort = () => { |
| 39 | + abortController.abort(); |
| 40 | + }; |
| 41 | + |
| 42 | + const signalInit = { |
| 43 | + signal: abortController.signal, |
| 44 | + }; |
| 45 | + |
| 46 | + const get = async <T>(url: string, init?: RequestInit): Promise<T> => { |
| 47 | + return await getJson(url, { |
| 48 | + ...signalInit, |
| 49 | + ...init, |
| 50 | + }); |
| 51 | + }; |
| 52 | + |
| 53 | + const post = async <T>(url: string, body: any, init?: RequestInit): Promise<T> => { |
| 54 | + return await postJson(url, body, { |
| 55 | + ...signalInit, |
| 56 | + ...init, |
| 57 | + }); |
| 58 | + }; |
| 59 | + |
| 60 | + return { get, post, abort }; |
| 61 | +}; |
0 commit comments