1
0
Code Issues Pull Requests Actions Packages Projects Releases Wiki Activity Security Code Quality

add lowdb

This commit is contained in:
2025-07-06 10:18:10 +07:00
parent 1b00f472a2
commit 99607fb75b
4 changed files with 160 additions and 0 deletions

33
src/database/database.ts Normal file
View File

@@ -0,0 +1,33 @@
import { Low } from "lowdb";
import { JSONFile } from "lowdb/node";
import { DBSchema } from "./database.schema";
import { defaultAdminUser } from "./defaultAdminUser";
import path from "path";
// File path for db.json
const file = path.resolve(process.cwd(), "src/database/db.json");
const adapter = new JSONFile<DBSchema>(file);
const db = new Low<DBSchema>(adapter, {
customers: [],
users: [],
customerDependants: [],
});
// Helper to generate next id for a collection
export function getNextId<T extends { id: number }>(items: T[]): number {
if (!items || items.length === 0) return 1;
return Math.max(...items.map((item) => item.id)) + 1;
}
// Initialize DB and ensure default admin user exists
export async function initDB() {
await db.read();
db.data ||= { customers: [], users: [], customerDependants: [] };
if (db.data.users.length === 0) {
db.data.users.push(defaultAdminUser);
await db.write();
}
}
export { db };