add lowdb
This commit is contained in:
33
src/database/database.ts
Normal file
33
src/database/database.ts
Normal 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 };
|
||||
Reference in New Issue
Block a user