Skip to content

Instantly share code, notes, and snippets.

@niyiAO
Last active October 4, 2021 07:27
Show Gist options
  • Save niyiAO/f383183525b353240c1599f7384cf4bb to your computer and use it in GitHub Desktop.
Save niyiAO/f383183525b353240c1599f7384cf4bb to your computer and use it in GitHub Desktop.
drop in wrapper around fetch
export class ResponseError extends Error {
status: number;
statusText: string;
data: any;
constructor(message: string, data: any, response: Response) {
super(message);
this.status = response.status;
this.statusText = response.statusText;
this.data = data;
}
static async create(response: Response) {
try {
const data = await response.json();
return new ResponseError(data.message, data, response);
} catch (error) {
if (error instanceof SyntaxError) {
const message = await response.text();
return new ResponseError(message, null, response);
}
throw error;
}
}
}
const baseUrl = "https://jsonplaceholder.typicode.com/";
type FetcherConfig = {
body?: any;
} & Omit<RequestInit, "body">;
const fetcher = async (url: string, customConfig?: FetcherConfig) => {
const config = {
method: customConfig?.body ? "GET" : "POST",
...customConfig,
body: customConfig?.body && JSON.stringify(customConfig.body),
headers: {
"Content-Type": "application/json",
...customConfig?.headers,
},
};
const response = await fetch(`${baseUrl}${url}`, config);
if (response.ok) {
const body = await response.json();
return body;
}
throw await ResponseError.create(response);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment