返回 CodeWhale
route.ts
根目录 / web / app / api / docs / search / [locale] / route.ts
1 import { getDocSearchSections } from "@/lib/docs-article-search";
2 import { isValidLocale } from "@/lib/i18n/config";
3
4 const responses = new Map<string, Promise<{ body: string; etag: string }>>();
5
6 export async function GET(request: Request, { params }: { params: Promise<{ locale: string }> }): Promise<Response> {
7 const { locale } = await params;
8 if (!isValidLocale(locale)) return Response.json({ error: "unknown_locale" }, { status: 404, headers: { "cache-control": "no-store" } });
9 try {
10 let pending = responses.get(locale);
11 if (!pending) {
12 pending = (async () => {
13 const body = JSON.stringify({ sections: getDocSearchSections(locale) });
14 const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(body));
15 const hash = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("");
16 return { body, etag: `W/"${hash}"` };
17 })();
18 responses.set(locale, pending);
19 }
20 const { body, etag } = await pending;
21 const headers = { "content-type": "application/json; charset=utf-8", "cache-control": "public, max-age=300, s-maxage=300", etag };
22 const validators = request.headers.get("if-none-match")?.split(",").map(value => value.trim()) ?? [];
23 return validators.some(value => value === "*" || value.replace(/^W\//, "") === etag.replace(/^W\//, ""))
24 ? new Response(null, { status: 304, headers })
25 : new Response(body, { headers });
26 } catch {
27 responses.delete(locale);
28 return Response.json({ error: "unavailable" }, { status: 503, headers: { "cache-control": "no-store" } });
29 }
30 }
31
31 lines TYPESCRIPT