import { DatabaseSync, type SQLOutputValue } from "node:sqlite"; import { Dump, type User } from "./interfaces.ts"; export const db = new DatabaseSync("api/sql/gerbeur.db"); /** * Database Row Types */ export interface DumpRow { id: string; title: string; description: string | null; user_id: string; created_at: string; [key: string]: SQLOutputValue; // Index signature } export interface UserRow { id: string; username: string; password_hash: string; is_admin: number; created_at: string; [key: string]: SQLOutputValue; // Index signature } /** * Type Guards */ export function isDumpRow(obj: Record): obj is DumpRow { return !!obj && typeof obj === "object" && "id" in obj && typeof obj.id === "string" && "title" in obj && typeof obj.title === "string" && "description" in obj && (typeof obj.description === "string" || obj.description === null) && "user_id" in obj && typeof obj.user_id === "string" && "created_at" in obj && typeof obj.created_at === "string"; } export function isUserRow(obj: Record): obj is UserRow { return !!obj && typeof obj === "object" && "id" in obj && typeof obj.id === "string" && "username" in obj && typeof obj.username === "string" && "password_hash" in obj && typeof obj.password_hash === "string" && "is_admin" in obj && typeof obj.is_admin === "number" && "created_at" in obj && typeof obj.created_at === "string"; } /** * Conversion Helpers */ export function dumpRowToApi( row: DumpRow, ): Dump { return { id: row.id, title: row.title, description: row.description ?? undefined, userId: row.user_id, createdAt: new Date(row.created_at), }; } export function dumpApiToRow(dump: Dump): DumpRow { return { id: dump.id, title: dump.title, description: dump.description ?? null, user_id: dump.userId, created_at: dump.createdAt.toISOString(), }; } export function userRowToApi(row: UserRow): User { return { id: row.id, username: row.username, passwordHash: row.password_hash, isAdmin: Boolean(row.is_admin), createdAt: new Date(row.created_at), }; } export function userApiToRow(user: User): UserRow { return { id: user.id, username: user.username, password_hash: user.passwordHash, is_admin: user.isAdmin ? 1 : 0, created_at: user.createdAt.toISOString(), }; }