Setup i18n and locale detection (#712)
* feat: setup translations * feat: i18n setup * Update pages/settings/profile.tsx Co-authored-by: Alex Johansson <[email protected]> * fix: abstract locale hook * fix: set default locale if preferred locale is not supported * Revert "fix: set default locale if preferred locale is not supported" This reverts commit e2a3d81371ee02a033520058a1d7d61cffeffc94. * fix: set default locale if preferred locale is not supported * fix: use 1 namespace and remove unnecessary logs * fix: yarn.lock * fix: linting errors Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: Alex Johansson <[email protected]>
This commit is contained in:
26 files changed
+801
-1685
No files matched your search
@@ -0,0 +1,71 @@
|
||||
import parser from "accept-language-parser";
|
||||
import { IncomingMessage } from "http";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
import { i18n } from "../../../next-i18next.config";
|
||||
|
||||
export const extractLocaleInfo = async (req: IncomingMessage) => {
|
||||
const session = await getSession({ req: req });
|
||||
const preferredLocale = parser.pick(i18n.locales, req.headers["accept-language"]);
|
||||
|
||||
if (session?.user?.id) {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: session.user.id,
|
||||
},
|
||||
select: {
|
||||
locale: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (user?.locale) {
|
||||
return user.locale;
|
||||
}
|
||||
|
||||
if (preferredLocale) {
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: session.user.id,
|
||||
},
|
||||
data: {
|
||||
locale: preferredLocale,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: session.user.id,
|
||||
},
|
||||
data: {
|
||||
locale: i18n.defaultLocale,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (preferredLocale) {
|
||||
return preferredLocale;
|
||||
}
|
||||
|
||||
return i18n.defaultLocale;
|
||||
};
|
||||
|
||||
interface localeType {
|
||||
[locale: string]: string;
|
||||
}
|
||||
|
||||
export const localeLabels: localeType = {
|
||||
en: "English",
|
||||
ro: "Romanian",
|
||||
};
|
||||
|
||||
export type OptionType = {
|
||||
value: string;
|
||||
label: string;
|
||||
};
|
||||
|
||||
export const localeOptions: OptionType[] = i18n.locales.map((locale) => {
|
||||
return { value: locale, label: localeLabels[locale] };
|
||||
});
|
||||
Reference in new issue
Block a user