Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | 12x 4x 2x 3x 3x 3x 3x 2x 1x 2x 3x 1x 2x 2x 9x 9x 9x 9x 9x 4x 2x | import type { EventHandlerRequest, H3Event } from "h3";
import { createError, getRouterParam } from "h3";
import { defineCachedEventHandler, useRuntimeConfig } from "nitropack/runtime";
import type { CachedEventHandlerOptions } from "nitropack";
import { ofetch } from "ofetch";
import createProvider from "#core/registry";
import {
TRANSLATIONS_MAX_AGE,
TRANSLATIONS_STALE_MAX_AGE,
type TranslationsConfig,
} from "#nuxt/config";
import type { TranslationMap } from "#core/domain/translations";
import { translationsKey } from "#core/translationsKey";
import {
TranslationsError,
TranslationsUnavailableError,
UndefinedLocaleError,
} from "#core/domain/errors";
import { OfetchHttpClient } from "#core/adapters/clients/OfetchHttpClient";
function assertLocale(locale: string | undefined, locales: string[]): asserts locale is string {
if (locale && locales.includes(locale)) return;
throw createError(new UndefinedLocaleError(locale));
}
const getKey = (event: H3Event<EventHandlerRequest>) => {
const locale = getRouterParam(event, "locale");
const { vendor, locales } = useRuntimeConfig(event).translations as TranslationsConfig;
assertLocale(locale, locales);
return translationsKey(vendor, locale);
};
const cacheOptions: CachedEventHandlerOptions<TranslationMap> = {
name: "translations",
group: "i18n",
maxAge: TRANSLATIONS_MAX_AGE,
staleMaxAge: TRANSLATIONS_STALE_MAX_AGE,
getKey,
shouldBypassCache: () => import.meta.dev === true,
};
const rethrowAsHttpError = (cause: unknown): never => {
if (cause instanceof TranslationsError) throw createError(cause);
throw cause;
};
const throwUnavailableError = (cause: unknown, locale: string): never => {
Eif (cause instanceof TranslationsError) throw createError(cause);
throw createError(new TranslationsUnavailableError(locale, cause));
};
export default defineCachedEventHandler<EventHandlerRequest, Promise<TranslationMap>>(
async (event) => {
const locale = getRouterParam(event, "locale");
const { vendor, locales } = useRuntimeConfig(event).translations as TranslationsConfig;
assertLocale(locale, locales);
const http = new OfetchHttpClient(ofetch.create({ baseURL: vendor.baseURL }));
const provider = await createProvider(vendor, http).catch(rethrowAsHttpError);
return provider
.getTranslations(locale)
.catch((cause) => throwUnavailableError(cause, locale));
},
cacheOptions,
);
|