cal.pub0.org/packages/lib/i18n.ts

31 lines
1.1 KiB
TypeScript
Raw Normal View History

/* eslint-disable @typescript-eslint/no-var-requires */
import parser from "accept-language-parser";
2023-08-22 12:34:55 +00:00
import type { GetServerSidePropsContext, NextApiRequest } from "next";
2023-08-22 12:34:55 +00:00
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import type { Maybe } from "@calcom/trpc/server";
const { i18n } = require("@calcom/config/next-i18next.config");
2023-08-22 12:34:55 +00:00
export async function getLocaleFromRequest(
req: NextApiRequest | GetServerSidePropsContext["req"]
): Promise<string> {
const session = await getServerSession({ req });
if (session?.user?.locale) return session.user.locale;
let preferredLocale: string | null | undefined;
if (req.headers["accept-language"]) {
2023-08-22 12:34:55 +00:00
preferredLocale = parser.pick(i18n.locales, req.headers["accept-language"], {
loose: true,
}) as Maybe<string>;
}
return preferredLocale ?? i18n.defaultLocale;
}
// Workaround for using router.locales from old router
export const locales = i18n.locales as string[];
export const localeOptions = locales.map((locale) => ({
value: locale,
label: new Intl.DisplayNames(locale, { type: "language" }).of(locale) || "",
}));