23 lines
961 B
TypeScript
23 lines
961 B
TypeScript
import * as i18next from "i18next";
|
|
import type { TFunction } from "i18next";
|
|
|
|
/**
|
|
* Shared indirection used by code that cannot receive a translator through
|
|
* props or a hook. On the server, the resolver is installed by the
|
|
* AsyncLocalStorage-backed request scope. In the browser (and outside an HTTP
|
|
* request), it falls back to the regular client-initialised i18next instance.
|
|
*/
|
|
export const REQUEST_TRANSLATOR_RESOLVER = Symbol.for("hivegrid.i18n.request-translator-resolver");
|
|
|
|
export type RequestTranslatorResolver = () => TFunction | undefined;
|
|
|
|
type GlobalWithRequestTranslator = typeof globalThis & {
|
|
[REQUEST_TRANSLATOR_RESOLVER]?: RequestTranslatorResolver;
|
|
};
|
|
|
|
export const requestScopedT = ((...args: unknown[]) => {
|
|
const resolver = (globalThis as GlobalWithRequestTranslator)[REQUEST_TRANSLATOR_RESOLVER];
|
|
const translator = resolver?.() ?? i18next.t;
|
|
return Reflect.apply(translator, undefined, args);
|
|
}) as unknown as TFunction;
|