/
Cooolprogrammers
/
web-nodejs-labs
Обзор
Документация
Войти
/
Cooolprogrammers
/
web-nodejs-labs
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
backend/src/routes/lab10/task3.js
67 строк
2 KB
darkvoid6@mail.ru
ЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫ
18 дек 2025, 07:59
18 дек 2025, 07:59
f2c4f06
Код
Авторство
О чём код?
// backend/src/routes/lab10/task3.js export default async function task3Routes(fastify) { // ✅ Оформление заказа из корзины fastify.post('/checkout', async (req, reply) => { const { items } = req.body; if (!items || !Array.isArray(items) || items.length === 0) { return reply.code(400).send({ error: 'Корзина пуста' }); } const client = await fastify.pg.connect(); try { await client.query('BEGIN'); const orderRes = await client.query( 'INSERT INTO lab10.orders DEFAULT VALUES RETURNING id' ); const orderId = orderRes.rows[0].id; for (const item of items) { const productRes = await client.query( 'SELECT title, price, amount FROM lab10.products WHERE id = $1 FOR UPDATE', [item.productId] ); const product = productRes.rows[0]; if (!product || product.amount < item.quantity) { throw new Error(`Недостаточно товара: ${product?.title}`); } await client.query( 'UPDATE lab10.products SET amount = amount - $1 WHERE id = $2', [item.quantity, item.productId] ); const total = product.price * item.quantity; await client.query(` INSERT INTO lab10.order_items (order_id, title, price, quantity, total_price) VALUES ($1, $2, $3, $4, $5) `, [ orderId, product.title, product.price, item.quantity, total ]); } await client.query('COMMIT'); return { success: true, orderId }; } catch (err) { await client.query('ROLLBACK'); return reply.code(400).send({ error: err.message }); } finally { client.release(); } }); }