feat: logger added
This commit is contained in:
parent
84663e65a0
commit
2490e9a21f
1 changed files with 28 additions and 1 deletions
|
|
@ -3,6 +3,7 @@ import { getValidSession } from "@/lib/auth/session";
|
|||
import { ApiError, type WinofyErrorDetails } from "./errors";
|
||||
|
||||
const BASE_URL = process.env.WINOFY_API_BASE_URL!;
|
||||
const DEBUG = process.env.NODE_ENV !== "production";
|
||||
|
||||
interface WinofyFetchOptions extends Omit<RequestInit, "body"> {
|
||||
/** Attach the caller's bearer token. Defaults to true — set false for public endpoints. */
|
||||
|
|
@ -18,8 +19,28 @@ export interface PaginatedResponse<T> {
|
|||
results: T[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Dev-only request/response logging — this is the terminal-equivalent of Chrome's
|
||||
* Network tab for these calls, since they run server-side and the browser never
|
||||
* sees them (no CORS on the Winofy API). Prints method/URL/body going out and
|
||||
* status/body coming back. Never runs in production (checked once via DEBUG,
|
||||
* and nothing here writes to a file or leaves the process).
|
||||
*/
|
||||
function logRequest(method: string, url: string, body: unknown) {
|
||||
if (!DEBUG) return;
|
||||
console.log(`\n→ [winofy] ${method} ${url}`);
|
||||
if (body !== undefined) console.log(" body:", JSON.stringify(body));
|
||||
}
|
||||
|
||||
function logResponse(method: string, url: string, status: number, data: unknown) {
|
||||
if (!DEBUG) return;
|
||||
console.log(`← [winofy] ${status} ${method} ${url}`);
|
||||
console.log(" data:", JSON.stringify(data));
|
||||
}
|
||||
|
||||
export async function winofyFetch<T>(path: string, options: WinofyFetchOptions = {}): Promise<T> {
|
||||
const { auth = true, params, headers, body, ...rest } = options;
|
||||
const method = rest.method ?? "GET";
|
||||
|
||||
const url = new URL(BASE_URL.replace(/\/$/, "") + path);
|
||||
if (params) {
|
||||
|
|
@ -39,6 +60,8 @@ export async function winofyFetch<T>(path: string, options: WinofyFetchOptions =
|
|||
if (session) finalHeaders.set("Authorization", `Bearer ${session.accessToken}`);
|
||||
}
|
||||
|
||||
logRequest(method, url.toString(), body);
|
||||
|
||||
const res = await fetch(url.toString(), {
|
||||
...rest,
|
||||
headers: finalHeaders,
|
||||
|
|
@ -46,9 +69,13 @@ export async function winofyFetch<T>(path: string, options: WinofyFetchOptions =
|
|||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (res.status === 204) return undefined as T;
|
||||
if (res.status === 204) {
|
||||
logResponse(method, url.toString(), res.status, null);
|
||||
return undefined as T;
|
||||
}
|
||||
|
||||
const data = await res.json().catch(() => null);
|
||||
logResponse(method, url.toString(), res.status, data);
|
||||
|
||||
if (!res.ok) {
|
||||
const envelope = data as { status_message?: string; details?: WinofyErrorDetails } | null;
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue