Skip to content

Instantly share code, notes, and snippets.

@OneOfOne
Created April 18, 2018 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OneOfOne/b9a46db71cb7d824e9fb705523a084e3 to your computer and use it in GitHub Desktop.
Save OneOfOne/b9a46db71cb7d824e9fb705523a084e3 to your computer and use it in GitHub Desktop.
Smaller wrapper over fetch
export let API_BASE: string = '/api/v1/';
export type FetchBodyType = Blob | Int8Array | Int16Array | Int32Array | Uint8Array |
Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array |
DataView | ArrayBuffer | FormData | string | null;
export type PayloadFn = (h: Headers) => FetchBodyType;
export type PayloadType = Blob | FormData | string | object | PayloadFn;
export const Fetch = async (url: string, method: string = 'GET', payload?: PayloadType): Promise<Response> => {
const req: RequestInit = {
method,
credentials: 'same-origin',
redirect: 'follow',
cache: 'no-cache',
referrerPolicy: 'origin-when-cross-origin',
mode: !url.startsWith('/') ? 'cors' : undefined,
headers: new Headers({
Accept: 'application/json',
}),
};
const h = (req.headers! as Headers);
if (payload instanceof FormData || payload instanceof Blob) {
req.body = payload;
} else if (typeof payload === 'string') {
req.body = payload;
} else if (typeof payload === 'function') {
req.body = payload(h);
} else if(payload != null) {
h.set('Content-Type', h.get('Accept') as string);
req.body = JSON.stringify(payload);
}
return await fetch(new Request(url, req));
};
export const FetchJSON = async <T>(url: string, method: string = 'GET', payload?: PayloadType): Promise<T> => {
const resp = await Fetch(url, method, payload);
return (await resp.json()) as T;
};
export const Get = <T>(ep: string) => FetchJSON<T>(API_BASE + ep);
export const Post = <T>(ep: string, payload?: PayloadType) => FetchJSON<T>(API_BASE + ep, 'POST', payload);
export const Put = <T>(ep: string, payload?: PayloadType) => FetchJSON<T>(API_BASE + ep, 'PUT', payload);
export const Delete = <T>(ep: string, payload?: PayloadType) => FetchJSON<T>(API_BASE + ep, 'DELETE', payload);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment