2021-09-23 08:49:17 +00:00
|
|
|
import parser from "accept-language-parser";
|
|
|
|
import { IncomingMessage } from "http";
|
|
|
|
|
|
|
|
import { getSession } from "@lib/auth";
|
|
|
|
import prisma from "@lib/prisma";
|
|
|
|
|
2021-10-14 19:22:01 +00:00
|
|
|
import { Maybe } from "@trpc/server";
|
|
|
|
|
2021-09-23 08:49:17 +00:00
|
|
|
import { i18n } from "../../../next-i18next.config";
|
|
|
|
|
2021-10-11 12:03:50 +00:00
|
|
|
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> => {
|
2021-10-08 11:43:48 +00:00
|
|
|
const session = await getSession({ req });
|
2021-10-12 13:11:33 +00:00
|
|
|
const preferredLocale = getLocaleFromHeaders(req);
|
2021-09-23 08:49:17 +00:00
|
|
|
|
|
|
|
if (session?.user?.id) {
|
|
|
|
const user = await prisma.user.findUnique({
|
|
|
|
where: {
|
|
|
|
id: session.user.id,
|
|
|
|
},
|
|
|
|
select: {
|
|
|
|
locale: true,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
if (user?.locale) {
|
|
|
|
return user.locale;
|
|
|
|
}
|
|
|
|
|
2021-10-12 13:11:33 +00:00
|
|
|
await prisma.user.update({
|
|
|
|
where: {
|
|
|
|
id: session.user.id,
|
|
|
|
},
|
|
|
|
data: {
|
|
|
|
locale: preferredLocale,
|
|
|
|
},
|
|
|
|
});
|
2021-09-23 08:49:17 +00:00
|
|
|
}
|
|
|
|
|
2021-10-12 13:11:33 +00:00
|
|
|
return preferredLocale;
|
2021-09-23 08:49:17 +00:00
|
|
|
};
|