mirror of
https://github.com/Xevion/xevion.dev.git
synced 2026-02-01 02:26:53 -06:00
Includes .dockerignore, Dockerfile with cargo-chef caching, and Justfile commands for building/running containerized app. Updates console-logger to support both JSON and pretty-printed logs based on LOG_JSON env var.
65 lines
1.6 KiB
TypeScript
65 lines
1.6 KiB
TypeScript
import { getLogger } from "@logtape/logtape";
|
|
import { env } from "$env/dynamic/private";
|
|
|
|
const logger = getLogger(["ssr", "lib", "api"]);
|
|
|
|
const upstreamUrl = env.UPSTREAM_URL;
|
|
const isUnixSocket =
|
|
upstreamUrl?.startsWith("/") || upstreamUrl?.startsWith("./");
|
|
const baseUrl = isUnixSocket ? "http://localhost" : upstreamUrl;
|
|
|
|
export async function apiFetch<T>(
|
|
path: string,
|
|
init?: RequestInit,
|
|
): Promise<T> {
|
|
if (!upstreamUrl) {
|
|
logger.error("UPSTREAM_URL environment variable not set");
|
|
throw new Error("UPSTREAM_URL environment variable not set");
|
|
}
|
|
|
|
const url = `${baseUrl}${path}`;
|
|
const method = init?.method ?? "GET";
|
|
|
|
const fetchOptions: RequestInit & { unix?: string } = {
|
|
...init,
|
|
signal: init?.signal ?? AbortSignal.timeout(30_000),
|
|
};
|
|
|
|
if (isUnixSocket) {
|
|
fetchOptions.unix = upstreamUrl;
|
|
}
|
|
|
|
logger.debug("API request", {
|
|
method,
|
|
url,
|
|
path,
|
|
isUnixSocket,
|
|
upstreamUrl,
|
|
});
|
|
|
|
try {
|
|
const response = await fetch(url, fetchOptions);
|
|
|
|
if (!response.ok) {
|
|
logger.error("API request failed", {
|
|
method,
|
|
url,
|
|
status: response.status,
|
|
statusText: response.statusText,
|
|
});
|
|
throw new Error(`API error: ${response.status} ${response.statusText}`);
|
|
}
|
|
|
|
const data = await response.json();
|
|
logger.debug("API response", { method, url, status: response.status });
|
|
return data;
|
|
} catch (error) {
|
|
logger.error("API request exception", {
|
|
method,
|
|
url,
|
|
error: error instanceof Error ? error.message : String(error),
|
|
});
|
|
throw error;
|
|
}
|
|
}
|