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