Skip to content

Instantly share code, notes, and snippets.

@chrisoverstreet
Last active October 1, 2020 13:22
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 chrisoverstreet/09633dd5aa63e5360aa2c426d89483d8 to your computer and use it in GitHub Desktop.
Save chrisoverstreet/09633dd5aa63e5360aa2c426d89483d8 to your computer and use it in GitHub Desktop.
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());
},
};
}
@chrisoverstreet
Copy link
Author

chrisoverstreet commented Oct 1, 2020

Usage:

v2('/markets').get()
  .then((data) => {
    // Do something with data
  }) ;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment