Files
descrybe/apps/web/src/lib/admin-translations.ts
T

77 lines
2.1 KiB
TypeScript
Raw Normal View History

import { ApiError } from "$lib/api";
import type { LocaleCoverage } from "$lib/i18n/coverage";
import type { MessageDict } from "$lib/i18n/messages/types";
export type TranslationsCatalogResponse = {
base_locale: string;
source_of_truth: string;
locales: { code: string; label: string; htmlLang: string }[];
keys: string[];
catalog: Record<string, MessageDict>;
coverage: LocaleCoverage[];
};
export type SaveTranslationsResponse = {
locale: string;
messages: MessageDict;
source_of_truth: string;
};
/** Same-origin SvelteKit route (not the Go API — do not use `api()`). */
const CATALOG_PATH = "/admin/translations/catalog";
async function webJson<T>(path: string, init?: RequestInit): Promise<T> {
const method = (init?.method ?? "GET").toUpperCase();
const headers: Record<string, string> = {
Accept: "application/json",
...(init?.headers as Record<string, string> | undefined)
};
if (method !== "GET" && method !== "HEAD" && init?.body !== undefined) {
headers["Content-Type"] = "application/json";
}
const res = await fetch(path, {
...init,
method,
credentials: "include",
headers
});
const text = await res.text();
let parsed: unknown = undefined;
if (text) {
try {
parsed = JSON.parse(text);
} catch {
parsed = text;
}
}
if (!res.ok) {
const message =
parsed && typeof parsed === "object" && typeof (parsed as { message?: unknown }).message === "string"
? (parsed as { message: string }).message
: res.statusText || "Request failed";
throw new ApiError(message, res.status, parsed);
}
return parsed as T;
}
export async function loadTranslationsCatalog(): Promise<TranslationsCatalogResponse> {
return webJson<TranslationsCatalogResponse>(CATALOG_PATH);
}
export async function saveTranslationUpdates(
locale: string,
updates: MessageDict
): Promise<SaveTranslationsResponse> {
return webJson<SaveTranslationsResponse>(CATALOG_PATH, {
method: "PATCH",
body: JSON.stringify({ locale, updates })
});
}
export function isTranslationsUnavailable(err: unknown): boolean {
return err instanceof ApiError && (err.status === 404 || err.status === 501);
}