calcom/lib/core/i18n/i18n.utils.ts
Alex van Andel ce8e9c126b
I18n's the i18n language dropdown & weekday using Intl (#955)
* I18n's the i18n language dropdown & weekday using Intl

* Some type fixes

* Trigger locale changes instantly (#958)

* Trigger locale changes instantly

* Restored types

* Capitalize languages across the board

Co-authored-by: Omar López <zomars@me.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2021-10-15 12:32:09 +01:00

46 lines
1.1 KiB
TypeScript

import parser from "accept-language-parser";
import { IncomingMessage } from "http";
import { getSession } from "@lib/auth";
import prisma from "@lib/prisma";
import { Maybe } from "@trpc/server";
import { i18n } from "../../../next-i18next.config";
export function getLocaleFromHeaders(req: IncomingMessage): string {
const preferredLocale = parser.pick(i18n.locales, req.headers["accept-language"]) as Maybe<string>;
return preferredLocale ?? i18n.defaultLocale;
}
export const getOrSetUserLocaleFromHeaders = async (req: IncomingMessage): Promise<string> => {
const session = await getSession({ req });
const preferredLocale = getLocaleFromHeaders(req);
if (session?.user?.id) {
const user = await prisma.user.findUnique({
where: {
id: session.user.id,
},
select: {
locale: true,
},
});
if (user?.locale) {
return user.locale;
}
await prisma.user.update({
where: {
id: session.user.id,
},
data: {
locale: preferredLocale,
},
});
}
return preferredLocale;
};