Last active
August 11, 2024 20:22
-
-
Save DouglasdeMoura/59ce418672d0e33dda7056b382b01de9 to your computer and use it in GitHub Desktop.
Tiny wrapper around fetch
This file contains 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
// 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
Nice! My simplified version looks like this: