code refactoring + add locale field to user table

This commit is contained in:
daniel31x13
2024-05-28 15:55:19 -04:00
parent 17cdb7efa4
commit deb6ed7ec8
4 changed files with 71 additions and 56 deletions
+2 -54
View File
@@ -5,10 +5,7 @@ import { User as U } from "@prisma/client";
import Link from "next/link";
import { useEffect, useState } from "react";
import { useTranslation } from "next-i18next";
import { GetServerSideProps } from "next";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import { useRouter } from "next/router";
import { i18n } from "next-i18next.config";
import getServerSideProps from "@/lib/client/getServerSideProps";
interface User extends U {
subscriptions: {
@@ -24,8 +21,6 @@ type UserModal = {
export default function Admin() {
const { t } = useTranslation();
const router = useRouter();
const { users, setUsers } = useUserStore();
const [searchQuery, setSearchQuery] = useState("");
@@ -39,7 +34,6 @@ export default function Admin() {
const [newUserModal, setNewUserModal] = useState(false);
useEffect(() => {
console.log(router);
setUsers();
}, []);
@@ -183,50 +177,4 @@ const UserListing = (
);
};
// Take this into a separate file, it's for logged out users
// For logged in users, we'll use their preferred language from the database (default: en)
export const getServerSideProps: GetServerSideProps = async (ctx) => {
console.log("CONTEXT", ctx);
const acceptLanguageHeader = ctx.req.headers["accept-language"];
const availableLanguages = i18n.locales;
console.log("ACCEPT LANGUAGE", acceptLanguageHeader);
console.log("AVAILABLE LANGUAGES", availableLanguages);
// Parse the accept-language header to get an array of languages
const acceptedLanguages = acceptLanguageHeader
?.split(",")
.map((lang) => lang.split(";")[0]);
console.log(acceptedLanguages);
// Find the best match between the accepted languages and available languages
let bestMatch = acceptedLanguages?.find((lang) =>
availableLanguages.includes(lang)
);
console.log(bestMatch);
// If no direct match, find the best partial match
if (!bestMatch) {
acceptedLanguages?.some((acceptedLang) => {
const partialMatch = availableLanguages.find((lang) =>
lang.startsWith(acceptedLang)
);
if (partialMatch) {
bestMatch = partialMatch;
return true;
}
return false;
});
}
console.log("BEST MATCH", bestMatch);
return {
props: {
...(await serverSideTranslations(bestMatch ?? "en", ["common"])),
},
};
};
export { getServerSideProps };