Improve error handling by creating a function handler for connections on servers that use KY, and use the status key in the response as the key to success instead of catch. Use catch if an error occurs between the client and server, not between the server and backend.
22 lines
466 B
TypeScript
22 lines
466 B
TypeScript
export const API_BASE_URL =
|
|
process.env.MAIN_BACKEND_API_URL ?? "http://localhost";
|
|
|
|
const apiFetch = async <T = unknown>(
|
|
path: string,
|
|
init?: RequestInit
|
|
): Promise<T> => {
|
|
const res = await fetch(`${API_BASE_URL}${path}`, {
|
|
...init,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
...init?.headers,
|
|
},
|
|
cache: "no-store",
|
|
});
|
|
|
|
if (!res.ok) throw new Error(await res.text());
|
|
return res.json();
|
|
};
|
|
|
|
export default apiFetch;
|