mirror of
https://github.com/Xevion/bus-reminder.git
synced 2025-12-06 17:14:34 -06:00
Setup API config POST route mechanisms
This commit is contained in:
@@ -20,6 +20,10 @@ export async function fetchConfiguration(
|
||||
return getParsed ? parsed : json;
|
||||
}
|
||||
|
||||
export async function setConfiguration(config: any): Promise<'OK'> {
|
||||
return redis.set('config', JSON.stringify(config));
|
||||
}
|
||||
|
||||
export function getKey(identifier: string, now: Date) {
|
||||
return format(now, 'yyyy-MM-dd') + ':' + identifier;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
import type {NextApiRequest, NextApiResponse} from 'next';
|
||||
import {env} from '@/env/server.mjs';
|
||||
import {fetchConfiguration} from "@/db";
|
||||
import {Configuration} from "@/timing";
|
||||
import type { NextApiRequest, NextApiResponse } from 'next';
|
||||
import { env } from '@/env/server.mjs';
|
||||
import { fetchConfiguration, setConfiguration } from '@/db';
|
||||
import { Configuration, ConfigurationSchema } from '@/timing';
|
||||
|
||||
type StatusData = { status: ResponseStatus };
|
||||
|
||||
type ResponseStatus =
|
||||
| 'unauthorized'
|
||||
| 'failed'
|
||||
| 'success';
|
||||
|
||||
type ResponseStatus = 'unauthorized' | 'invalid' | 'failed' | 'success';
|
||||
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
@@ -17,19 +13,28 @@ export default async function handler(
|
||||
) {
|
||||
if (req.query.key != env.API_KEY) {
|
||||
// auth failed
|
||||
res.status(401).json({status: 'unauthorized'});
|
||||
res.status(401).json({ status: 'unauthorized' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method == "GET") {
|
||||
if (req.method == 'GET') {
|
||||
try {
|
||||
const configuration = await fetchConfiguration();
|
||||
res.status(200).json(configuration);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
res.status(500).json({status: "failed"});
|
||||
res.status(500).json({ status: 'failed' });
|
||||
}
|
||||
} else if (req.method == "POST") {
|
||||
res.status(200).json({status: 'success'});
|
||||
} else if (req.method == 'POST') {
|
||||
const json = JSON.parse(req.body);
|
||||
const parsed = ConfigurationSchema.safeParse(json);
|
||||
if (parsed.success) {
|
||||
try {
|
||||
await setConfiguration(json);
|
||||
res.status(200).json({ status: 'success' });
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
res.status(500).json({ status: 'failed' });
|
||||
}
|
||||
} else res.status(400).json({ status: 'invalid' });
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user