From 16191a8dd29b82f41c752579eae55736ddc069e5 Mon Sep 17 00:00:00 2001 From: Hornwitser Date: Sat, 31 May 2025 23:10:25 +0200 Subject: [PATCH] Add debug route to delete the database To simplify development add a debug route to delete the database content so that it'll be re-generated to the demo schedule. --- server/api/admin/delete-database.post.ts | 20 ++++++++++++++++++++ server/database.ts | 19 ++++++++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 server/api/admin/delete-database.post.ts diff --git a/server/api/admin/delete-database.post.ts b/server/api/admin/delete-database.post.ts new file mode 100644 index 0000000..1809ced --- /dev/null +++ b/server/api/admin/delete-database.post.ts @@ -0,0 +1,20 @@ +import { deleteDatbase, readAccounts } from "~/server/database"; + +export default defineEventHandler(async (event) => { + const session = await requireAccountSession(event); + let accounts = await readAccounts(); + const sessionAccount = accounts.find( + account => account.id === session.accountId + ); + if (!sessionAccount) { + throw Error("Account does not exist"); + } + if (sessionAccount.type !== "admin") { + throw createError({ + statusCode: 403, + statusMessage: "Forbidden", + }); + } + + await deleteDatbase(); +}) diff --git a/server/database.ts b/server/database.ts index e98379a..598ac40 100644 --- a/server/database.ts +++ b/server/database.ts @@ -1,4 +1,4 @@ -import { readFile, writeFile } from "node:fs/promises"; +import { readFile, unlink, writeFile } from "node:fs/promises"; import { Schedule } from "~/shared/types/schedule"; import { Account, Subscription, Session } from "~/shared/types/account"; import { generateDemoSchedule, generateDemoAccounts } from "./generate-demo-schedule"; @@ -13,6 +13,23 @@ const nextAccountIdPath = "data/next-account-id.json"; const sessionsPath = "data/sessions.json"; const nextSessionIdPath = "data/next-session-id.json"; +async function remove(path: string) { + try { + await unlink(path); + } catch (err: any) { + if (err.code !== "ENOENT") { + throw err; + } + } +} + +export async function deleteDatbase() { + await remove(schedulePath); + await remove(subscriptionsPath); + await remove(accountsPath); + await remove(sessionsPath); +} + async function readJson(filePath: string, fallback: T) { let data: T extends () => infer R ? R : T; try {