Last active
October 1, 2020 13:22
-
-
Save chrisoverstreet/09633dd5aa63e5360aa2c426d89483d8 to your computer and use it in GitHub Desktop.
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
type Result<Response> = { | |
get(): Promise<Response>; | |
delete(): Promise<Response>; | |
post(body?: BodyInit): Promise<Response>; | |
put(body?: BodyInit): Promise<Response>; | |
patch(body?: BodyInit): Promise<Response>; | |
}; | |
type Options = { | |
headers?: Record<string, string>; | |
params?: Record<string, string>; | |
}; | |
export async function checkForV2Error(response: Response): Promise<Response> { | |
if (!response.ok) { | |
throw new Error( | |
(await response.json())?.error?.message ?? 'Request failed', | |
); | |
} | |
return response; | |
} | |
export function v2<Response = any>( | |
endpoint: string, | |
options: Options = {}, | |
): Result<Response> { | |
const { headers, params } = options; | |
let input = `/v2/${endpoint}`; | |
if (params) { | |
input += `?${new URLSearchParams(params).toString()}`; | |
} | |
const init: RequestInit = { | |
headers, | |
}; | |
return { | |
get(): Promise<Response> { | |
return fetch(input, init) | |
.then(checkForV2Error) | |
.then((response) => response.json()); | |
}, | |
delete(): Promise<Response> { | |
return fetch(input, { | |
...init, | |
method: 'DELETE', | |
}) | |
.then(checkForV2Error) | |
.then((response) => response.json()); | |
}, | |
post(body?: BodyInit): Promise<Response> { | |
return fetch(input, { | |
...init, | |
headers: { | |
ContentType: 'application/json', | |
'X-CSRF-Token': typeof window !== 'undefined' && window.__CSRF_TOKEN, | |
...(init.headers || {}), | |
}, | |
method: 'POST', | |
body, | |
}) | |
.then(checkForV2Error) | |
.then((response) => response.json()); | |
}, | |
put(body?: BodyInit): Promise<Response> { | |
return fetch(input, { | |
...init, | |
headers: { | |
ContentType: 'application/json', | |
...(init.headers || {}), | |
}, | |
method: 'PUT', | |
body, | |
}) | |
.then(checkForV2Error) | |
.then((response) => response.json()); | |
}, | |
patch(body?: BodyInit): Promise<Response> { | |
return fetch(input, { | |
...init, | |
headers: { | |
ContentType: 'application/json', | |
...(init.headers || {}), | |
}, | |
method: 'PATCH', | |
body, | |
}) | |
.then(checkForV2Error) | |
.then((response) => response.json()); | |
}, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: