Files

41 lines
1.2 KiB
TypeScript

export const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://127.0.0.1:8000/api";
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const response = await fetch(`${API_BASE}${path}`, {
...init,
cache: "no-store",
headers: {
"Content-Type": "application/json",
...(init?.headers ?? {})
}
});
if (!response.ok) {
let message = `${response.status} ${response.statusText}`;
try {
const body = await response.json();
message = body.detail ?? message;
} catch {
// keep response status as message
}
throw new Error(message);
}
return response.json() as Promise<T>;
}
export const api = {
get: <T>(path: string) => request<T>(path),
post: <T>(path: string, body: unknown = {}) =>
request<T>(path, { method: "POST", body: JSON.stringify(body) }),
patch: <T>(path: string, body: unknown) =>
request<T>(path, { method: "PATCH", body: JSON.stringify(body) })
};
export function formatDateTime(value: string | null | undefined) {
if (!value) return "-";
return new Intl.DateTimeFormat("zh-CN", {
dateStyle: "short",
timeStyle: "short"
}).format(new Date(value));
}