Add database initialization

now, when the project is ran without configured database,
it will prompt for the first user to configure
the database and add the first user
This commit is contained in:
Wroclaw 2023-06-14 13:00:19 +02:00
parent cbfc4e9317
commit 90932a49c8
6 changed files with 286 additions and 0 deletions

View file

@ -0,0 +1,15 @@
/* global defineEventHandler */
import { data, database } from "../utils/database";
export async function isFirstRun() {
const [tables] = await database.query({ sql: "SHOW TABLES", rowsAsArray: true }, []) as data<[string]>;
if (tables.length === 0) return true;
if (!tables.find(a => a[0] === "users")) return true;
const [[users]] = await database.query("SELECT COUNT(*) as `count` FROM `users`") as data<{count: number}>;
if (users.count === 0) return true;
return false;
}
export default defineEventHandler((e) => {
return isFirstRun();
});

View file

@ -0,0 +1,33 @@
/* global defineEventHandler, setResponseStatus, readBody, createError */
import fs from "node:fs/promises";
import { database as db } from "../utils/database";
import { isFirstRun } from "./firstRun.get";
import { getPasswordHash } from "./login.post";
import Snowflake from "~/utils/snowflake";
export default defineEventHandler(async (e) => {
if (!isFirstRun()) {
setResponseStatus(e, 404);
return "";
}
const body = await readBody(e);
if (typeof body !== "object") throw createError({ message: "Invalid body", statusCode: 400 });
const username = body.username;
if (typeof username !== "string") throw createError({ message: "username is not string", statusCode: 400 });
const password = body.password;
if (typeof password !== "string") throw createError({ message: "password is not string", statusCode: 400 });
const email = body.email;
if (typeof email !== "string") throw createError({ message: "email is not string", statusCode: 400 });
const sql = await fs.readFile("./schemaModel.sql", "utf-8");
const database = await db.new({ multipleStatements: true });
await database.query(sql);
await database.execute(
"INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES (?, ?, ?, ?)",
[new Snowflake().toString(), username, getPasswordHash(password), email]);
return "";
});