/
Coderdev
/
web-nodejs-labs
Обзор
Документация
Войти
/
Coderdev
/
web-nodejs-labs
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
backend/src/services/lab9/product.service.js
106 строк
3 KB
Coderdev
1
23 апр 2026, 22:48
23 апр 2026, 22:48
fe8b855
Код
Авторство
О чём код?
class ProductService { async getAll(pg) { const { rows } = await pg.query('SELECT * FROM lab9.products ORDER BY id DESC'); return rows; } async search(pg, q) { const { rows } = await pg.query( 'SELECT * FROM lab9.products WHERE LOWER(title) LIKE LOWER($1) ORDER BY id DESC', [`%${q}%`] ); return rows; } async getStock(pg) { const { rows } = await pg.query(` SELECT COUNT(*)::int AS total_products, COALESCE(SUM(amount), 0)::int AS total_items, COALESCE(SUM(price * amount), 0)::bigint AS total_value FROM lab9.products `); return rows[0]; } async getById(pg, id) { const { rows } = await pg.query('SELECT * FROM lab9.products WHERE id = $1', [id]); return rows[0]; } async create(pg, data) { const { title, price, amount } = data; const { rows } = await pg.query( 'INSERT INTO lab9.products (title, price, amount) VALUES ($1, $2, $3) RETURNING *', [title, price, amount] ); return rows[0]; } async update(pg, id, data) { const { title, price, amount } = data; const { rows } = await pg.query( 'UPDATE lab9.products SET title = $1, price = $2, amount = $3 WHERE id = $4 RETURNING *', [title, price, amount, id] ); return rows[0]; } async delete(pg, id) { const { rows } = await pg.query('DELETE FROM lab9.products WHERE id = $1 RETURNING id', [id]); return rows[0]; } async verifyCart(pg, items) { const problems = []; for (const item of items) { const product = await this.getById(pg, item.id); if (!product) { problems.push({ id: item.id, error: 'Product not found', available: 0 }); continue; } if (item.qty < 1 || item.qty > 5) { problems.push({ id: item.id, title: product.title, error: 'Invalid quantity', available: product.amount }); continue; } if (product.amount < item.qty) { problems.push({ id: item.id, title: product.title, error: 'Not enough stock', available: product.amount, requested: item.qty }); } } return { ok: problems.length === 0, items: problems }; } async buy(pg, items) { const client = await pg.connect(); try { await client.query('BEGIN'); const verify = await this.verifyCart(client, items); if (!verify.ok) { await client.query('ROLLBACK'); return { ok: false, items: verify.items }; } const purchased = []; for (const item of items) { const { rows } = await client.query( 'UPDATE lab9.products SET amount = amount - $1 WHERE id = $2 RETURNING *', [item.qty, item.id] ); purchased.push({ id: rows[0].id, title: rows[0].title, bought: item.qty, remaining: rows[0].amount, price: rows[0].price }); } await client.query('COMMIT'); return { ok: true, purchased }; } catch (error) { await client.query('ROLLBACK'); throw error; } finally { client.release(); } } } export default new ProductService();