create-product.ts
TypeScript · 33 рядків
1// POST /api/products — новий товар (бренд + SKU) з центрального поля сторінки, коли SKU ще немає в каталозі.
2// Строк придатності береться з категорії, якщо не задано. Дубль бренд + SKU → 409 DUPLICATE (UNIQUE (brand_id, sku)).
3import { z } from 'zod';
4import { DomainError } from '../domain/errors.ts';
5import { feature } from '../platform/http.ts';
6import { id } from '../platform/schema.ts';
7
8export const CreateProductInput = z.object({
9 brandId: id,
10 sku: z.string().trim().min(1).max(40),
11 name: z.string().trim().min(1).max(200),
12 categoryId: id,
13 shelfLifeDays: z.number().int().positive().nullish(),
14});
15
16export default feature({
17 name: 'createProduct',
18 method: 'POST',
19 path: '/api/products',
20 summary: 'Створити товар бренд + SKU',
21 input: CreateProductInput,
22 tx: 'write',
23 run: async (sql, input) => {
24 const [row] = await sql.query(`
25 INSERT INTO stock.product (brand_id, sku, name, category_id, shelf_life_days)
26 SELECT :brandId, :sku, :name, c.id, coalesce(:shelfLifeDays::int, c.shelf_life_days)
27 FROM stock.category c WHERE c.id = :categoryId
28 RETURNING id, brand_id, sku, name, category_id, shelf_life_days`, { ...input, shelfLifeDays: input.shelfLifeDays ?? null });
29 if (!row) throw new DomainError('CATEGORY_NOT_FOUND', `Категорії ${input.categoryId} немає`);
30 return row;
31 },
32});
33