Skip to content

Instantly share code, notes, and snippets.

@alinz
Created July 7, 2019 13:49
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 alinz/fdd3d987ffb40f95e012e451cd15a7d0 to your computer and use it in GitHub Desktop.
Save alinz/fdd3d987ffb40f95e012e451cd15a7d0 to your computer and use it in GitHub Desktop.
A simple Fetch implementation
const baseURL = process.env.API_ADDR || 'http://localhost/api'
export type Pagination<T> = {
meta: {
total: number
}
data: T
}
export interface Fetcher {
get<T>(path: string, jwt: string): Promise<T>
post<T>(path: string, jwt: string, data?: any): Promise<T>
put<T>(path: string, jwt: string, data?: any): Promise<T>
delete<T>(path: string, jwt: string, data?: any): Promise<T>
}
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE'
const call = async <T>(path: string, method: Method, jwt: string, data: any): Promise<T> => {
const initConfig: { [key: string]: any } = {
mode: 'cors',
credentials: 'include',
method,
}
if (data) {
initConfig.body = typeof data !== 'string' ? JSON.stringify(data) : data
}
if (jwt && jwt !== '') {
initConfig.headers['Authorization'] = `BEARER ${jwt}`
}
const resp = await fetch(path, initConfig)
// since status 204 (No Content) should not have any payload,
// we will return right away
if (resp.status === 204) {
return
}
const body = await resp.json()
if (resp.status >= 400) {
throw { code: resp.status, error: body.error }
}
return body as T
}
class DefaultFetcher implements Fetcher {
host: string
constructor(host: string) {
this.host = host
}
get = <T>(path: string, jwt: string): Promise<T> => {
return call<T>(`${this.host}${path}`, 'GET', jwt, undefined)
}
post = <T>(path: string, jwt: string, data: any = undefined): Promise<T> => {
return call<T>(`${this.host}${path}`, 'POST', jwt, data)
}
put = <T>(path: string, jwt: string, data: any = undefined): Promise<T> => {
return call<T>(`${this.host}${path}`, 'PUT', jwt, data)
}
delete = <T>(path: string, jwt: string, data: any = undefined): Promise<T> => {
return call<T>(`${this.host}${path}`, 'DELETE', jwt, data)
}
}
export default new DefaultFetcher(baseURL) as Fetcher
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment