Skip to content

Instantly share code, notes, and snippets.

@joel-daros
Forked from DouglasdeMoura/api.ts
Created April 1, 2024 15:00
Show Gist options
  • Save joel-daros/318fe156b1bb078466de7ed1a271291a to your computer and use it in GitHub Desktop.
Save joel-daros/318fe156b1bb078466de7ed1a271291a to your computer and use it in GitHub Desktop.
Tiny wrapper around fetch
// Extends the return of the HTTPError class
class HTTPError extends Error {
readonly response: any;
readonly status: number;
readonly statusText: string;
constructor(status: number, statusText: string, response: any) {
super(statusText);
this.status = status;
this.statusText = statusText;
this.response = response;
}
}
const createQuery =
(baseURL: RequestInfo | URL = '', baseInit?: RequestInit) =>
<TResponse = unknown>(url: RequestInfo | URL, init?: RequestInit) =>
fetch(`${baseURL}${url}`, { ...baseInit, ...init }).then(async (res) => {
// Now, we get the JSON response early
const response = await res.json()
if (!res.ok)
throw new HTTPError(res.status, res.statusText, response);
return response as TResponse
})
// In this function, we define our base URL and headers.
const query = createQuery(
'https://dummyjson.com',
{
headers: {
'Content-Type': 'application/json',
// 'Authorization': `Bearer ${getToken()}`, // If you need to add a token to the header, you can do it here.
},
})
const makeRequest = (method: RequestInit['method']) =>
<TResponse = unknown, TBody = Record<string, unknown>>(url: RequestInfo | URL, body: TBody) =>
query<TResponse>(url, {
method,
body: JSON.stringify(body),
})
export const api = {
get: query,
post: makeRequest('POST'),
delete: makeRequest('DELETE'),
put: makeRequest('PUT'),
patch: makeRequest('PATCH'),
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment