59 lines
2.1 KiB
TypeScript
59 lines
2.1 KiB
TypeScript
// Auto-generated Book service
|
|
import { queryAll, queryOne, execute } from "../db/client.js";
|
|
import type { Book, CreateBookInput, UpdateBookInput } from "../types/index.js";
|
|
|
|
export class BookService {
|
|
/** List all books */
|
|
list(): Book[] {
|
|
return queryAll<Book>("SELECT * FROM books ORDER BY created_at DESC");
|
|
}
|
|
|
|
/** Get by ID */
|
|
getById(id: string): Book | undefined {
|
|
return queryOne<Book>("SELECT * FROM books WHERE id = ?", [id]);
|
|
}
|
|
|
|
/** Create */
|
|
create(input: CreateBookInput): Book {
|
|
const id = crypto.randomUUID();
|
|
const now = new Date().toISOString();
|
|
const hasCreatedAt = true;
|
|
const hasUpdatedAt = true;
|
|
const cols = ["id", "user_id", "title", "description", "status", "data", "created_at", "updated_at"];
|
|
const placeholders = cols.map(() => "?").join(", ");
|
|
const values = [id, input.userId ?? null, input.title ?? null, input.description ?? null, input.status ?? null, input.data ?? null, now, now];
|
|
|
|
execute(`INSERT INTO books (${cols.join(", ")}) VALUES (${placeholders})`, values);
|
|
return this.getById(id)!;
|
|
}
|
|
|
|
/** Update */
|
|
update(id: string, input: UpdateBookInput): Book | undefined {
|
|
const existing = this.getById(id);
|
|
if (!existing) return undefined;
|
|
|
|
const sets: string[] = [];
|
|
const values: unknown[] = [];
|
|
if (input.userId !== undefined) { sets.push("user_id = ?"); values.push(input.userId); }
|
|
if (input.title !== undefined) { sets.push("title = ?"); values.push(input.title); }
|
|
if (input.description !== undefined) { sets.push("description = ?"); values.push(input.description); }
|
|
if (input.status !== undefined) { sets.push("status = ?"); values.push(input.status); }
|
|
if (input.data !== undefined) { sets.push("data = ?"); values.push(input.data); }
|
|
|
|
if (sets.length === 0) return existing;
|
|
|
|
sets.push("updated_at = ?");
|
|
values.push(new Date().toISOString());
|
|
|
|
values.push(id);
|
|
execute(`UPDATE books SET ${sets.join(", ")} WHERE id = ?`, values);
|
|
return this.getById(id)!;
|
|
}
|
|
|
|
/** Delete */
|
|
delete(id: string): boolean {
|
|
const result = execute("DELETE FROM books WHERE id = ?", [id]);
|
|
return result.changes > 0;
|
|
}
|
|
}
|