Created
February 25, 2022 17:59
-
-
Save iethree/1730e158f63b7f4d8539d205ee014dd2 to your computer and use it in GitHub Desktop.
Generic API fetching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// generic API fetching | |
const BASE_URL = '/api/'; | |
const handleResponse = async (r: Response) => { | |
try { | |
if (r.ok) { | |
return r.json(); | |
} | |
return Promise.reject(await r.json()); | |
} catch (e) { | |
return Promise.reject(new Error(`received an error from ${r.url}`)); | |
} | |
}; | |
const defaultOptions: { | |
credentials: RequestCredentials | undefined, | |
headers: { [key: string]: string }, | |
} = { | |
credentials: 'same-origin', | |
headers: { 'Content-Type': 'application/json' }, | |
}; | |
export function get(endpoint: string) { | |
return fetch(`${BASE_URL}${endpoint}`, { | |
...defaultOptions, | |
method: 'GET', | |
}).then(handleResponse); | |
} | |
/* eslint-disable @typescript-eslint/no-explicit-any */ | |
export function put(endpoint: string, body: any) { | |
return fetch(`${BASE_URL}${endpoint}`, { | |
method: 'PUT', | |
body: JSON.stringify(body), | |
...defaultOptions, | |
}).then(handleResponse); | |
} | |
export function post(endpoint: string, body: any) { | |
return fetch(`${BASE_URL}${endpoint}`, { | |
method: 'POST', | |
body: JSON.stringify(body), | |
...defaultOptions, | |
}).then(handleResponse); | |
} | |
export function fetchDelete(endpoint: string, body: any = {}) { | |
return fetch(`${BASE_URL}${endpoint}`, { | |
method: 'DELETE', | |
body: JSON.stringify(body), | |
...defaultOptions, | |
}).then(handleResponse); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment