🎉 init: 小龙的工作空间
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
// Auto-generated Pet service
|
||||
import { queryAll, queryOne, execute } from "../db/client.js";
|
||||
import type { Pet, CreatePetInput, UpdatePetInput } from "../types/index.js";
|
||||
|
||||
export class PetService {
|
||||
/** List all pets */
|
||||
list(): Pet[] {
|
||||
return queryAll<Pet>("SELECT * FROM pets ORDER BY created_at DESC");
|
||||
}
|
||||
|
||||
/** Get by ID */
|
||||
getById(id: string): Pet | undefined {
|
||||
return queryOne<Pet>("SELECT * FROM pets WHERE id = ?", [id]);
|
||||
}
|
||||
|
||||
/** Create */
|
||||
create(input: CreatePetInput): Pet {
|
||||
const id = crypto.randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const hasCreatedAt = true;
|
||||
const hasUpdatedAt = false;
|
||||
const cols = ["id", "owner_id", "name", "species", "breed", "birth_date", "weight_kg", "avatar_url", "created_at"];
|
||||
const placeholders = cols.map(() => "?").join(", ");
|
||||
const values = [id, input.ownerId ?? null, input.name ?? null, input.species ?? null, input.breed ?? null, input.birthDate ?? null, input.weightKg ?? null, input.avatarUrl ?? null, now];
|
||||
|
||||
execute(`INSERT INTO pets (${cols.join(", ")}) VALUES (${placeholders})`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Update */
|
||||
update(id: string, input: UpdatePetInput): Pet | undefined {
|
||||
const existing = this.getById(id);
|
||||
if (!existing) return undefined;
|
||||
|
||||
const sets: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
if (input.ownerId !== undefined) { sets.push("owner_id = ?"); values.push(input.ownerId); }
|
||||
if (input.name !== undefined) { sets.push("name = ?"); values.push(input.name); }
|
||||
if (input.species !== undefined) { sets.push("species = ?"); values.push(input.species); }
|
||||
if (input.breed !== undefined) { sets.push("breed = ?"); values.push(input.breed); }
|
||||
if (input.birthDate !== undefined) { sets.push("birth_date = ?"); values.push(input.birthDate); }
|
||||
if (input.weightKg !== undefined) { sets.push("weight_kg = ?"); values.push(input.weightKg); }
|
||||
if (input.avatarUrl !== undefined) { sets.push("avatar_url = ?"); values.push(input.avatarUrl); }
|
||||
|
||||
if (sets.length === 0) return existing;
|
||||
|
||||
|
||||
|
||||
values.push(id);
|
||||
execute(`UPDATE pets SET ${sets.join(", ")} WHERE id = ?`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Delete */
|
||||
delete(id: string): boolean {
|
||||
const result = execute("DELETE FROM pets WHERE id = ?", [id]);
|
||||
return result.changes > 0;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user