35 lines
1.0 KiB
TypeScript
35 lines
1.0 KiB
TypeScript
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: [],
|
|
userPermissions: [],
|
|
permissions: [],
|
|
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: [], userPermissions: [], permissions: [] };
|
|
if (db.data.users.length === 0) {
|
|
db.data.users.push(defaultAdminUser);
|
|
await db.write();
|
|
}
|
|
}
|
|
|
|
export { db };
|