我为NextJS 13设置了一个使用typescript的fetch功能。由于我是Typescript的新手,我想问一下这是否是一个正确的方法和/或我是否忽略了一些东西。
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 });
}
字符串
page.tsx
//imports
const { products } = await _get<ProductsType>(
`${process.env.CLIENT_API_URL}/products`
);
//return
型
types.d.ts
type ProductType = {
id: number;
title: string;
description: string;
price: number;
// other properties
};
型
1条答案
按热度按时间mnemlml81#
你写了几个函数来帮助你发送GET/POST请求,这种方法没有错。这是否是最佳实践取决于您和您的项目。你知道,提供一些帮助功能将帮助我们更快地编写代码,但它也带来了一些限制。