49 lines
1.6 KiB
TypeScript
49 lines
1.6 KiB
TypeScript
import lobbyCatalog from '../../../shared/i18n/lobby.json';
|
|
|
|
const frontendErrors = lobbyCatalog.frontend.errors;
|
|
const localeConfig = lobbyCatalog.locales;
|
|
|
|
type FrontendErrorKey = keyof typeof frontendErrors;
|
|
type SupportedLocale = (typeof localeConfig.supported)[number];
|
|
|
|
function isFrontendErrorKey(value: string): value is FrontendErrorKey {
|
|
return value in frontendErrors;
|
|
}
|
|
|
|
function normalizeLocale(rawLocale?: string): SupportedLocale {
|
|
const requested = (rawLocale ?? '').trim().toLowerCase();
|
|
if (localeConfig.supported.includes(requested as SupportedLocale)) {
|
|
return requested as SupportedLocale;
|
|
}
|
|
return localeConfig.default;
|
|
}
|
|
|
|
export function lobbyMessage(key: FrontendErrorKey, locale?: string): string {
|
|
const resolvedLocale = normalizeLocale(locale);
|
|
const translations = frontendErrors[key] as Record<string, string>;
|
|
|
|
if (translations[resolvedLocale]) {
|
|
return translations[resolvedLocale];
|
|
}
|
|
if (translations[localeConfig.default]) {
|
|
return translations[localeConfig.default];
|
|
}
|
|
|
|
return key;
|
|
}
|
|
|
|
export function lobbyMessageFromApiPayload(payload: unknown, fallbackKey: FrontendErrorKey, locale?: string): string {
|
|
if (!payload || typeof payload !== 'object') {
|
|
return lobbyMessage(fallbackKey, locale);
|
|
}
|
|
|
|
const record = payload as Record<string, unknown>;
|
|
const code = typeof record.error_code === 'string' ? record.error_code : '';
|
|
const payloadLocale = typeof record.locale === 'string' ? record.locale : locale;
|
|
if (!isFrontendErrorKey(code)) {
|
|
return lobbyMessage(fallbackKey, payloadLocale);
|
|
}
|
|
|
|
return lobbyMessage(code, payloadLocale);
|
|
}
|