Case-insensitive lang search for i8n, along with support for match just lang, without region, ie. 'en' == 'en-US'

This commit is contained in:
simojenki
2021-08-16 10:50:56 +10:00
parent c67f74bf08
commit 2cfd52415c
5 changed files with 114 additions and 68 deletions

View File

@@ -106,6 +106,13 @@ const translations: Record<LANG, Record<KEY, string>> = {
},
};
const translationsLookup = Object.keys(translations).reduce((lookups, lang) => {
lookups.set(lang, translations[lang as LANG]);
lookups.set(lang.toLocaleLowerCase(), translations[lang as LANG]);
lookups.set(lang.toLocaleLowerCase().split("-")[0]!, translations[lang as LANG]);
return lookups;
}, new Map<string, Record<KEY, string>>())
export const randomLang = () => _.shuffle(["en-US", "nl-NL"])[0]!;
export const asLANGs = (acceptLanguageHeader: string | undefined) =>
@@ -134,8 +141,8 @@ export const keys = (lang: LANG = "en-US") => Object.keys(translations[lang]);
export default (serviceName: string): I8N =>
(...langs: string[]): Lang => {
const langToUse =
langs.map((l) => translations[l as LANG]).find((it) => it) ||
const langToUse =
langs.map((l) => translationsLookup.get(l as LANG)).find((it) => it) ||
translations["en-US"];
return (key: KEY) => {
const value = langToUse[key]?.replace(

View File

@@ -87,7 +87,10 @@ function server(
app.set("view engine", "eta");
app.set("views", "./web/views");
const langFor = (req: Request) => i8n(...asLANGs(req.headers["accept-language"]))
const langFor = (req: Request) => {
logger.debug(`${req.path} (req[accept-language]=${req.headers["accept-language"]})`);
return i8n(...asLANGs(req.headers["accept-language"]));
}
app.get("/", (req, res) => {
const lang = langFor(req);

View File

@@ -536,9 +536,10 @@ function bindSmapiSoapServiceToExpress(
.then(splitId(id))
.then(({ musicLibrary, accessToken, type, typeId }) => {
const paging = { _index: index, _count: count };
const lang = i8n((headers["accept-language"] || "en-US") as LANG);
const acceptLanguage = headers["accept-language"];
const lang = i8n((acceptLanguage || "en-US") as LANG);
logger.debug(
`Fetching metadata type=${type}, typeId=${typeId}, lang=${lang}`
`Fetching metadata type=${type}, typeId=${typeId}, acceptLanguage=${acceptLanguage}`
);
const albums = (q: AlbumQuery): Promise<GetMetadataResponse> =>