Skip to content

Instantly share code, notes, and snippets.

@HynekS
Forked from DouglasdeMoura/api.ts
Created March 6, 2024 20:37
Show Gist options
  • Save HynekS/ba61aa1636252402d1f35a3adb16e3c4 to your computer and use it in GitHub Desktop.
Save HynekS/ba61aa1636252402d1f35a3adb16e3c4 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