Recently, I implemented a fetch feature using TypeScript for my NextJS 13 project. As I am still getting familiar with TypeScript, I wanted to double-check if my approach is correct and if there are any potential oversights.
Here is the code snippet from utils.ts:
enum HTTPMethods {
GET = "GET",
POST = "POST",
PUT = "PUT",
PATCH = "PATCH",
DELETE = "DELETE",
}
function handleError(status: number, message: string) {
throw new Error(`${status}: ${message}`);
}
async function request<TResponse>(
url: string,
config: RequestInit
): Promise<TResponse> {
const response = await fetch(url, config);
if (!response.ok) {
handleError(response.status, response.statusText);
}
return await response.json();
}
export async function _get<TResponse>(url: string): Promise<TResponse> {
return request<TResponse>(url, { method: HTTPMethods.GET });
}
export async function _post<TBody extends BodyInit, TResponse>(
url: string,
body: TBody
): Promise<TResponse> {
return request<TResponse>(url, { method: HTTPMethods.POST, body });
}
Inside page.tsx:
//imports
const { products } = await _get<ProductsType>(
`${process.env.CLIENT_API_URL}/products`
);
//return
Lastly, in types.d.ts:
type ProductType = {
id: number;
title: string;
description: string;
price: number;
// other properties
};