0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-01-27 21:39:16 -05:00
logto/packages/core/src/routes/phrase.ts

46 lines
1.7 KiB
TypeScript
Raw Normal View History

import { isBuiltInLanguageTag } from '@logto/phrases-ui';
import { adminConsoleApplicationId, adminConsoleSignInExperience } from '@logto/schemas';
2022-10-21 13:14:17 +08:00
import type { Provider } from 'oidc-provider';
2022-11-21 16:38:24 +08:00
import detectLanguage from '#src/i18n/detect-language.js';
2022-12-14 13:23:59 +08:00
import { getPhrase } from '#src/libraries/phrase.js';
2022-11-21 16:38:24 +08:00
import { findAllCustomLanguageTags } from '#src/queries/custom-phrase.js';
import { findDefaultSignInExperience } from '#src/queries/sign-in-experience.js';
2022-11-21 16:38:24 +08:00
import type { AnonymousRouter } from './types.js';
const getLanguageInfo = async (applicationId: unknown) => {
if (applicationId === adminConsoleApplicationId) {
return adminConsoleSignInExperience.languageInfo;
}
const { languageInfo } = await findDefaultSignInExperience();
return languageInfo;
};
export default function phraseRoutes<T extends AnonymousRouter>(router: T, provider: Provider) {
router.get('/phrase', async (ctx, next) => {
const interaction = await provider
.interactionDetails(ctx.req, ctx.res)
// Should not block when failed to get interaction
.catch(() => null);
const applicationId = interaction?.params.client_id;
const { autoDetect, fallbackLanguage } = await getLanguageInfo(applicationId);
const detectedLanguages = autoDetect ? detectLanguage(ctx) : [];
const acceptableLanguages = [...detectedLanguages, fallbackLanguage];
const customLanguages = await findAllCustomLanguageTags();
const language =
acceptableLanguages.find(
(tag) => isBuiltInLanguageTag(tag) || customLanguages.includes(tag)
) ?? 'en';
ctx.set('Content-Language', language);
ctx.body = await getPhrase(language, customLanguages);
return next();
});
}