2021-08-26 09:35:11 -07:00
|
|
|
import {parse as languageParser} from "accept-language-parser";
|
2022-06-04 00:12:30 -04:00
|
|
|
import {IncomingMessage} from 'http';
|
2021-08-26 09:35:11 -07:00
|
|
|
import {locales} from 'app/common/Locales';
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Returns the locale from a request, falling back to `defaultLocale`
|
|
|
|
|
* if unable to determine the locale.
|
|
|
|
|
*/
|
2022-06-04 00:12:30 -04:00
|
|
|
export function localeFromRequest(req: IncomingMessage, defaultLocale: string = 'en-US') {
|
2021-08-26 09:35:11 -07:00
|
|
|
const language = languageParser(req.headers["accept-language"] as string)[0];
|
|
|
|
|
if (!language) { return defaultLocale; }
|
|
|
|
|
|
|
|
|
|
const locale = `${language.code}-${language.region}`;
|
|
|
|
|
const supports = locales.some(l => l.code === locale);
|
|
|
|
|
return supports ? locale : defaultLocale;
|
|
|
|
|
}
|