🐛 Fix slug page and refactor server side translations code

This commit is contained in:
Manuel Ruwe
2022-12-30 16:51:53 +01:00
parent 0565d444d2
commit fe662ab166
4 changed files with 59 additions and 47 deletions

View File

@@ -1,31 +1,27 @@
import { getCookie } from 'cookies-next';
import fs from 'fs';
import { GetServerSidePropsContext } from 'next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import path from 'path';
import { useEffect } from 'react';
import LoadConfigComponent from '../components/Config/LoadConfig';
import { Dashboard } from '../components/Dashboard/Dashboard';
import Layout from '../components/layout/Layout';
import { useConfigContext } from '../config/provider';
import { useConfigStore } from '../config/store';
import { getConfig } from '../tools/getConfig';
import { useInitConfig } from '../config/init';
import { getFrontendConfig } from '../tools/config/getFrontendConfig';
import { getServerSideTranslations } from '../tools/getServerSideTranslations';
import { dashboardNamespaces } from '../tools/translation-namespaces';
import { ConfigType } from '../types/config';
type ServerSideProps = {
config: ConfigType;
};
import { DashboardServerSideProps } from '../types/dashboardPageType';
export async function getServerSideProps({
req,
res,
locale,
query,
}: GetServerSidePropsContext): Promise<{ props: ServerSideProps }> {
const configByUrl = query.slug;
const configPath = path.join(process.cwd(), 'data/configs', `${configByUrl}.json`);
}: GetServerSidePropsContext): Promise<{ props: DashboardServerSideProps }> {
const configName = query.slug as string;
const configPath = path.join(process.cwd(), 'data/configs', `${configName}.json`);
const configExists = fs.existsSync(configPath);
const translations = await getServerSideTranslations(req, res, dashboardNamespaces, locale);
if (!configExists) {
// Redirect to 404
res.writeHead(301, { Location: '/404' });
@@ -64,26 +60,26 @@ export async function getServerSideProps({
wrappers: [],
widgets: [],
},
configName,
...translations,
},
};
}
const configLocale = getCookie('config-locale', { req, res });
const targetLanguage = (configLocale ?? locale) as string;
const translations = await serverSideTranslations(targetLanguage, dashboardNamespaces);
return getConfig(configByUrl as string, translations);
const config = getFrontendConfig(configName as string);
return {
props: {
configName,
config,
...translations,
},
};
}
export default function HomePage(props: any) {
const { config: initialConfig }: { config: ConfigType } = props;
const { name: configName } = useConfigContext();
const { updateConfig } = useConfigStore();
useEffect(() => {
if (!configName) {
return;
}
updateConfig(configName, () => initialConfig);
}, [initialConfig]);
export default function HomePage({ config: initialConfig }: DashboardServerSideProps) {
useInitConfig(initialConfig);
return (
<Layout>
<Dashboard />