full update
This commit is contained in:
32
src/lib/api/fetchApiJson.ts
Normal file
32
src/lib/api/fetchApiJson.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { getApiBaseUrl } from "@/components/main/BaseUrl";
|
||||
|
||||
type FetchApiJsonResult<T> = {
|
||||
ok: boolean;
|
||||
status: number;
|
||||
data: T | null;
|
||||
};
|
||||
|
||||
export async function fetchApiJson<T>(
|
||||
path: string,
|
||||
options?: RequestInit
|
||||
): Promise<FetchApiJsonResult<T>> {
|
||||
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
||||
const url = `${getApiBaseUrl()}${normalizedPath}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
cache: "no-store",
|
||||
...options,
|
||||
});
|
||||
|
||||
const contentType = response.headers.get("content-type") || "";
|
||||
if (!contentType.includes("application/json")) {
|
||||
return { ok: false, status: response.status, data: null };
|
||||
}
|
||||
|
||||
const data = (await response.json()) as T;
|
||||
return { ok: response.ok, status: response.status, data };
|
||||
} catch {
|
||||
return { ok: false, status: 0, data: null };
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ export const UPSTREAM_API =
|
||||
|
||||
type ProxyOptions = {
|
||||
stripAuth?: boolean;
|
||||
cacheable?: boolean;
|
||||
};
|
||||
|
||||
const PUBLIC_AUTH_PATTERNS = [
|
||||
@@ -46,13 +47,26 @@ export async function proxyToUpstream(
|
||||
method,
|
||||
headers,
|
||||
body,
|
||||
cache: "no-store",
|
||||
cache: options?.cacheable ? "force-cache" : "no-store",
|
||||
});
|
||||
|
||||
const responseHeaders = new Headers();
|
||||
const upstreamType = upstream.headers.get("content-type");
|
||||
if (upstreamType) responseHeaders.set("content-type", upstreamType);
|
||||
|
||||
const acceptRanges = upstream.headers.get("accept-ranges");
|
||||
if (acceptRanges) responseHeaders.set("accept-ranges", acceptRanges);
|
||||
|
||||
const contentLength = upstream.headers.get("content-length");
|
||||
if (contentLength) responseHeaders.set("content-length", contentLength);
|
||||
|
||||
if (options?.cacheable && upstream.ok) {
|
||||
responseHeaders.set(
|
||||
"Cache-Control",
|
||||
"public, max-age=31536000, immutable"
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(upstream.body, {
|
||||
status: upstream.status,
|
||||
headers: responseHeaders,
|
||||
|
||||
Reference in New Issue
Block a user