mirror of
https://github.com/logto-io/logto.git
synced 2025-01-27 21:39:16 -05:00
827123faa0
* feat(core): integrate basic sentinel * chore: add integration tests * refactor(test): fix toast matching * chore: add changeset * refactor(test): update naming
36 lines
1.2 KiB
TypeScript
36 lines
1.2 KiB
TypeScript
import type { MiddlewareType } from 'koa';
|
|
import type { IRouterParamContext } from 'koa-router';
|
|
|
|
import detectLanguage from '#src/i18n/detect-language.js';
|
|
import { i18next } from '#src/utils/i18n.js';
|
|
|
|
type LanguageUtils = {
|
|
formatLanguageCode(code: string): string;
|
|
isSupportedCode(code: string): boolean;
|
|
};
|
|
|
|
export type WithI18nContext<ContextT extends IRouterParamContext = IRouterParamContext> =
|
|
ContextT & {
|
|
locale: string;
|
|
};
|
|
|
|
export default function koaI18next<
|
|
StateT,
|
|
ContextT extends IRouterParamContext,
|
|
ResponseBodyT,
|
|
>(): MiddlewareType<StateT, WithI18nContext<ContextT>, ResponseBodyT> {
|
|
return async (ctx, next) => {
|
|
const languages = detectLanguage(ctx);
|
|
// Cannot patch type def directly, see https://github.com/microsoft/TypeScript/issues/36146
|
|
// eslint-disable-next-line no-restricted-syntax
|
|
const languageUtils = i18next.services.languageUtils as LanguageUtils;
|
|
const foundLanguage = languages
|
|
.map((code) => languageUtils.formatLanguageCode(code))
|
|
.find((code) => languageUtils.isSupportedCode(code));
|
|
|
|
await i18next.changeLanguage(foundLanguage);
|
|
ctx.locale = i18next.language;
|
|
|
|
return next();
|
|
};
|
|
}
|