Basic backend support and config loading from file

This commit is contained in:
Aj - Thomas
2022-05-12 19:28:10 +02:00
parent e61e986028
commit 91f636ca97
10 changed files with 235 additions and 46 deletions

View File

@@ -16,7 +16,7 @@ export default function App(props: AppProps & { colorScheme: ColorScheme }) {
const toggleColorScheme = (value?: ColorScheme) => {
const nextColorScheme = value || (colorScheme === 'dark' ? 'light' : 'dark');
setColorScheme(nextColorScheme);
setCookies('mantine-color-scheme', nextColorScheme, { maxAge: 60 * 60 * 24 * 30 });
setCookies('color-scheme', nextColorScheme, { maxAge: 60 * 60 * 24 * 30 });
};
return (
@@ -50,5 +50,5 @@ export default function App(props: AppProps & { colorScheme: ColorScheme }) {
}
App.getInitialProps = ({ ctx }: { ctx: GetServerSidePropsContext }) => ({
colorScheme: getCookie('mantine-color-scheme', ctx) || 'light',
colorScheme: getCookie('color-scheme', ctx) || 'light',
});

View File

@@ -0,0 +1,61 @@
import { NextApiRequest, NextApiResponse } from 'next';
import fs from 'fs';
import path from 'path';
function Put(req: NextApiRequest, res: NextApiResponse) {
// Get the slug of the request
const { slug } = req.query as { slug: string };
// Get the body of the request
const { body }: { body: string } = req;
if (!slug || !body) {
res.status(400).json({
error: 'Wrong request',
});
}
// Save the body in the /data/config folder with the slug as filename
fs.writeFileSync(
path.join('data/configs', `${slug}.json`),
JSON.stringify(body, null, 2),
'utf8'
);
return res.status(200).json({
message: 'Configuration saved with success',
});
}
function Get(req: NextApiRequest, res: NextApiResponse) {
// Get the slug of the request
const { slug } = req.query as { slug: string };
if (!slug) {
return res.status(400).json({
message: 'Wrong request',
});
}
// Loop over all the files in the /data/configs directory
const files = fs.readdirSync('data/configs');
// Strip the .json extension from the file name
const configs = files.map((file) => file.replace('.json', ''));
// If the target is not in the list of files, return an error
if (!configs.includes(slug)) {
return res.status(404).json({
message: 'Target not found',
});
}
// Return the content of the file
return res.status(200).json(fs.readFileSync(path.join('data/configs', `${slug}.json`), 'utf8'));
}
export default async (req: NextApiRequest, res: NextApiResponse) => {
// Filter out if the reuqest is a Put or a GET
if (req.method === 'PUT') {
return Put(req, res);
}
if (req.method === 'GET') {
return Get(req, res);
}
return res.status(405).json({
statusCode: 405,
message: 'Method not allowed',
});
};

View File

@@ -0,0 +1,28 @@
import { NextApiRequest, NextApiResponse } from 'next';
import fs from 'fs';
function Get(req: NextApiRequest, res: NextApiResponse) {
// Loop over all the files in the /data/configs directory
const files = fs.readdirSync('data/configs');
// Strip the .json extension from the file name
const configs = files.map((file) => file.replace('.json', ''));
// Return the list of files
return res.status(200).json(configs);
}
export default async (req: NextApiRequest, res: NextApiResponse) => {
// Filter out if the reuqest is a POST or a GET
if (req.method === 'POST') {
return res.status(405).json({
statusCode: 405,
message: 'Method not allowed',
});
}
if (req.method === 'GET') {
return Get(req, res);
}
return res.status(405).json({
statusCode: 405,
message: 'Method not allowed',
});
};

52
pages/tryconfig.tsx Normal file
View File

@@ -0,0 +1,52 @@
import { getCookie, setCookies } from 'cookies-next';
import { GetServerSidePropsContext } from 'next/types';
import fs from 'fs';
import path from 'path';
import { Button, JsonInput, Space } from '@mantine/core';
import { useEffect, useState } from 'react';
import axios from 'axios';
import { showNotification } from '@mantine/notifications';
import { Config } from '../tools/types';
import { useConfig } from '../tools/state';
export async function getServerSideProps({ req, res }: GetServerSidePropsContext) {
let cookie = getCookie('config-name', { req, res });
if (!cookie) {
setCookies('config-name', 'default', { req, res, maxAge: 60 * 60 * 24 * 30 });
cookie = 'default';
}
const config = fs.readFileSync(path.join('data/configs', `${cookie}.json`), 'utf8');
return {
props: {
config: JSON.parse(config),
},
};
}
export default function TryConfig(props: any) {
const { config: initialConfig }: { config: Config } = props;
const { config, loadConfig, setConfig } = useConfig();
const [value, setValue] = useState(JSON.stringify(config, null, 2));
useEffect(() => {
setValue(JSON.stringify(config, null, 2));
// setConfig(initialConfig);
}, [config]);
return (
<div>
<h1>Try Config</h1>
<p>
This page is a demo of the <code>config</code> API.
</p>
<p>
The <code>config</code> API is a way to store configuration data in a JSON file.
</p>
<JsonInput autosize onChange={setValue} value={value} />
<Space my="xl" />
<Button onClick={() => loadConfig('cringe')}>Load config cringe</Button>
<Button onClick={() => loadConfig('default')}>Load config default</Button>
<Button onClick={() => setConfig(JSON.parse(value))}>Save config</Button>
</div>
);
}