Created
April 18, 2018 15:52
-
-
Save OneOfOne/b9a46db71cb7d824e9fb705523a084e3 to your computer and use it in GitHub Desktop.
Smaller wrapper over fetch
This file contains 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
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