feat: PostgreSQL 17 вместо SQLite
pg + connect-pg-simple, async routes, docker-compose, скрипт setup-postgres. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
+87
-67
@@ -1,15 +1,16 @@
|
||||
const express = require('express');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const { db } = require('../db');
|
||||
const { query, formatPrice } = require('../db');
|
||||
const { getCart, cartCount } = require('../cart');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { asyncHandler } = require('../utils/asyncHandler');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.use((req, res, next) => {
|
||||
const cart = getCart(req);
|
||||
res.locals.cartCount = cartCount(cart);
|
||||
res.locals.formatPrice = require('../db').formatPrice;
|
||||
res.locals.formatPrice = formatPrice;
|
||||
next();
|
||||
});
|
||||
|
||||
@@ -18,50 +19,54 @@ router.get('/register', (req, res) => {
|
||||
res.render('register', { title: 'Регистрация', error: null, values: {} });
|
||||
});
|
||||
|
||||
router.post('/register', (req, res) => {
|
||||
const { name, email, password, password2 } = req.body;
|
||||
const values = { name, email };
|
||||
router.post(
|
||||
'/register',
|
||||
asyncHandler(async (req, res) => {
|
||||
const { name, email, password, password2 } = req.body;
|
||||
const values = { name, email };
|
||||
|
||||
if (!name?.trim() || !email?.trim() || !password) {
|
||||
return res.status(400).render('register', {
|
||||
title: 'Регистрация',
|
||||
error: 'Заполните все поля',
|
||||
values,
|
||||
});
|
||||
}
|
||||
if (password.length < 6) {
|
||||
return res.status(400).render('register', {
|
||||
title: 'Регистрация',
|
||||
error: 'Пароль не менее 6 символов',
|
||||
values,
|
||||
});
|
||||
}
|
||||
if (password !== password2) {
|
||||
return res.status(400).render('register', {
|
||||
title: 'Регистрация',
|
||||
error: 'Пароли не совпадают',
|
||||
values,
|
||||
});
|
||||
}
|
||||
|
||||
const hash = bcrypt.hashSync(password, 10);
|
||||
try {
|
||||
const r = db
|
||||
.prepare('INSERT INTO users (email, password_hash, name) VALUES (?, ?, ?)')
|
||||
.run(email.trim().toLowerCase(), hash, name.trim());
|
||||
req.session.userId = r.lastInsertRowid;
|
||||
res.redirect('/');
|
||||
} catch (err) {
|
||||
if (err.code === 'SQLITE_CONSTRAINT_UNIQUE') {
|
||||
if (!name?.trim() || !email?.trim() || !password) {
|
||||
return res.status(400).render('register', {
|
||||
title: 'Регистрация',
|
||||
error: 'Этот email уже зарегистрирован',
|
||||
error: 'Заполните все поля',
|
||||
values,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
if (password.length < 6) {
|
||||
return res.status(400).render('register', {
|
||||
title: 'Регистрация',
|
||||
error: 'Пароль не менее 6 символов',
|
||||
values,
|
||||
});
|
||||
}
|
||||
if (password !== password2) {
|
||||
return res.status(400).render('register', {
|
||||
title: 'Регистрация',
|
||||
error: 'Пароли не совпадают',
|
||||
values,
|
||||
});
|
||||
}
|
||||
|
||||
const hash = bcrypt.hashSync(password, 10);
|
||||
try {
|
||||
const { rows } = await query(
|
||||
'INSERT INTO users (email, password_hash, name) VALUES ($1, $2, $3) RETURNING id',
|
||||
[email.trim().toLowerCase(), hash, name.trim()]
|
||||
);
|
||||
req.session.userId = rows[0].id;
|
||||
res.redirect('/');
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
return res.status(400).render('register', {
|
||||
title: 'Регистрация',
|
||||
error: 'Этот email уже зарегистрирован',
|
||||
values,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
router.get('/login', (req, res) => {
|
||||
if (req.session.userId) return res.redirect('/account');
|
||||
@@ -73,27 +78,31 @@ router.get('/login', (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
router.post('/login', (req, res) => {
|
||||
const { email, password } = req.body;
|
||||
const next = req.body.next || '/';
|
||||
const values = { email };
|
||||
router.post(
|
||||
'/login',
|
||||
asyncHandler(async (req, res) => {
|
||||
const { email, password } = req.body;
|
||||
const next = req.body.next || '/';
|
||||
const values = { email };
|
||||
|
||||
const user = db
|
||||
.prepare('SELECT * FROM users WHERE email = ?')
|
||||
.get((email || '').trim().toLowerCase());
|
||||
const { rows } = await query('SELECT * FROM users WHERE email = $1', [
|
||||
(email || '').trim().toLowerCase(),
|
||||
]);
|
||||
const user = rows[0];
|
||||
|
||||
if (!user || !bcrypt.compareSync(password || '', user.password_hash)) {
|
||||
return res.status(401).render('login', {
|
||||
title: 'Вход',
|
||||
error: 'Неверный email или пароль',
|
||||
next,
|
||||
values,
|
||||
});
|
||||
}
|
||||
if (!user || !bcrypt.compareSync(password || '', user.password_hash)) {
|
||||
return res.status(401).render('login', {
|
||||
title: 'Вход',
|
||||
error: 'Неверный email или пароль',
|
||||
next,
|
||||
values,
|
||||
});
|
||||
}
|
||||
|
||||
req.session.userId = user.id;
|
||||
res.redirect(next.startsWith('/') ? next : '/');
|
||||
});
|
||||
req.session.userId = user.id;
|
||||
res.redirect(next.startsWith('/') ? next : '/');
|
||||
})
|
||||
);
|
||||
|
||||
router.post('/logout', (req, res) => {
|
||||
req.session.destroy(() => {
|
||||
@@ -101,16 +110,27 @@ router.post('/logout', (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/account', requireAuth, (req, res) => {
|
||||
const user = db
|
||||
.prepare('SELECT id, email, name, created_at FROM users WHERE id = ?')
|
||||
.get(req.session.userId);
|
||||
router.get(
|
||||
'/account',
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { rows } = await query(
|
||||
'SELECT id, email, name, created_at FROM users WHERE id = $1',
|
||||
[req.session.userId]
|
||||
);
|
||||
const user = rows[0];
|
||||
|
||||
const orderCount = db
|
||||
.prepare('SELECT COUNT(*) AS n FROM orders WHERE user_id = ?')
|
||||
.get(user.id).n;
|
||||
const countResult = await query(
|
||||
'SELECT COUNT(*)::int AS n FROM orders WHERE user_id = $1',
|
||||
[user.id]
|
||||
);
|
||||
|
||||
res.render('account', { title: 'Личный кабинет', user, orderCount });
|
||||
});
|
||||
res.render('account', {
|
||||
title: 'Личный кабинет',
|
||||
user,
|
||||
orderCount: countResult.rows[0].n,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
const express = require('express');
|
||||
const { db } = require('../db');
|
||||
const { checkConnection } = require('../db');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.get('/health', (_req, res) => {
|
||||
router.get('/health', async (_req, res) => {
|
||||
try {
|
||||
db.prepare('SELECT 1').get();
|
||||
res.json({ ok: true, service: 'shop' });
|
||||
await checkConnection();
|
||||
res.json({ ok: true, service: 'shop', database: 'postgresql' });
|
||||
} catch (err) {
|
||||
res.status(503).json({ ok: false, error: err.message });
|
||||
}
|
||||
|
||||
+239
-206
@@ -1,7 +1,8 @@
|
||||
const express = require('express');
|
||||
const { db, formatPrice } = require('../db');
|
||||
const { query, pool, formatPrice } = require('../db');
|
||||
const { getCart, cartCount, cartItems, cartTotal } = require('../cart');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { asyncHandler } = require('../utils/asyncHandler');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -16,120 +17,135 @@ router.use((req, res, next) => {
|
||||
next();
|
||||
});
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
const category = req.query.category || '';
|
||||
const q = (req.query.q || '').trim();
|
||||
router.get(
|
||||
'/',
|
||||
asyncHandler(async (req, res) => {
|
||||
const category = req.query.category || '';
|
||||
const q = (req.query.q || '').trim();
|
||||
|
||||
let sql = `
|
||||
SELECT p.*, c.name AS category_name, c.slug AS category_slug
|
||||
FROM products p
|
||||
LEFT JOIN categories c ON c.id = p.category_id
|
||||
WHERE p.stock > 0
|
||||
`;
|
||||
const params = [];
|
||||
let sql = `
|
||||
SELECT p.*, c.name AS category_name, c.slug AS category_slug
|
||||
FROM products p
|
||||
LEFT JOIN categories c ON c.id = p.category_id
|
||||
WHERE p.stock > 0
|
||||
`;
|
||||
const params = [];
|
||||
let n = 1;
|
||||
|
||||
if (category) {
|
||||
sql += ' AND c.slug = ?';
|
||||
params.push(category);
|
||||
}
|
||||
if (q) {
|
||||
sql += ' AND (p.name LIKE ? OR p.description LIKE ?)';
|
||||
const like = `%${q}%`;
|
||||
params.push(like, like);
|
||||
}
|
||||
sql += ' ORDER BY p.name';
|
||||
if (category) {
|
||||
sql += ` AND c.slug = $${n++}`;
|
||||
params.push(category);
|
||||
}
|
||||
if (q) {
|
||||
sql += ` AND (p.name ILIKE $${n} OR p.description ILIKE $${n})`;
|
||||
params.push(`%${q}%`);
|
||||
n++;
|
||||
}
|
||||
sql += ' ORDER BY p.name';
|
||||
|
||||
const products = db.prepare(sql).all(...params);
|
||||
const categories = db.prepare('SELECT * FROM categories ORDER BY name').all();
|
||||
const { rows: products } = await query(sql, params);
|
||||
const { rows: categories } = await query('SELECT * FROM categories ORDER BY name');
|
||||
|
||||
res.render('home', {
|
||||
title: 'Каталог',
|
||||
products,
|
||||
categories,
|
||||
activeCategory: category,
|
||||
searchQuery: q,
|
||||
});
|
||||
});
|
||||
res.render('home', {
|
||||
title: 'Каталог',
|
||||
products,
|
||||
categories,
|
||||
activeCategory: category,
|
||||
searchQuery: q,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
router.get('/product/:slug', (req, res) => {
|
||||
const product = db
|
||||
.prepare(
|
||||
router.get(
|
||||
'/product/:slug',
|
||||
asyncHandler(async (req, res) => {
|
||||
const { rows } = await query(
|
||||
`SELECT p.*, c.name AS category_name, c.slug AS category_slug
|
||||
FROM products p
|
||||
LEFT JOIN categories c ON c.id = p.category_id
|
||||
WHERE p.slug = ?`
|
||||
)
|
||||
.get(req.params.slug);
|
||||
WHERE p.slug = $1`,
|
||||
[req.params.slug]
|
||||
);
|
||||
const product = rows[0];
|
||||
|
||||
if (!product) {
|
||||
return res.status(404).render('error', {
|
||||
title: 'Не найдено',
|
||||
message: 'Товар не найден',
|
||||
code: 404,
|
||||
if (!product) {
|
||||
return res.status(404).render('error', {
|
||||
title: 'Не найдено',
|
||||
message: 'Товар не найден',
|
||||
code: 404,
|
||||
});
|
||||
}
|
||||
|
||||
res.render('product', { title: product.name, product });
|
||||
})
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/cart',
|
||||
asyncHandler(async (req, res) => {
|
||||
const cart = getCart(req);
|
||||
const items = await cartItems(cart);
|
||||
const total = cartTotal(items);
|
||||
const errorMsg = req.query.error ? decodeURIComponent(String(req.query.error)) : null;
|
||||
|
||||
res.render('cart', {
|
||||
title: 'Корзина',
|
||||
items,
|
||||
total,
|
||||
error: errorMsg,
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
res.render('product', { title: product.name, product });
|
||||
});
|
||||
router.post(
|
||||
'/cart/add',
|
||||
asyncHandler(async (req, res) => {
|
||||
const productId = parseInt(req.body.product_id, 10);
|
||||
const quantity = Math.max(1, parseInt(req.body.quantity, 10) || 1);
|
||||
|
||||
router.get('/cart', (req, res) => {
|
||||
const cart = getCart(req);
|
||||
const items = cartItems(db, cart);
|
||||
const total = cartTotal(items);
|
||||
|
||||
const errorMsg = req.query.error ? decodeURIComponent(String(req.query.error)) : null;
|
||||
res.render('cart', {
|
||||
title: 'Корзина',
|
||||
items,
|
||||
total,
|
||||
error: errorMsg,
|
||||
});
|
||||
});
|
||||
|
||||
router.post('/cart/add', (req, res) => {
|
||||
const productId = parseInt(req.body.product_id, 10);
|
||||
const quantity = Math.max(1, parseInt(req.body.quantity, 10) || 1);
|
||||
|
||||
const product = db
|
||||
.prepare('SELECT id, stock FROM products WHERE id = ?')
|
||||
.get(productId);
|
||||
if (!product) {
|
||||
return res.redirect('/');
|
||||
}
|
||||
|
||||
const cart = getCart(req);
|
||||
const current = cart[productId] || 0;
|
||||
const nextQty = Math.min(product.stock, current + quantity);
|
||||
cart[productId] = nextQty;
|
||||
|
||||
const redirect = req.body.redirect || '/cart';
|
||||
res.redirect(redirect);
|
||||
});
|
||||
|
||||
router.post('/cart/update', (req, res) => {
|
||||
const cart = getCart(req);
|
||||
const updates = req.body.items || {};
|
||||
|
||||
for (const [id, qty] of Object.entries(updates)) {
|
||||
const productId = parseInt(id, 10);
|
||||
const quantity = parseInt(qty, 10);
|
||||
if (!productId) continue;
|
||||
|
||||
if (!quantity || quantity <= 0) {
|
||||
delete cart[productId];
|
||||
continue;
|
||||
const { rows } = await query('SELECT id, stock FROM products WHERE id = $1', [
|
||||
productId,
|
||||
]);
|
||||
const product = rows[0];
|
||||
if (!product) {
|
||||
return res.redirect('/');
|
||||
}
|
||||
|
||||
const product = db
|
||||
.prepare('SELECT stock FROM products WHERE id = ?')
|
||||
.get(productId);
|
||||
if (product) {
|
||||
cart[productId] = Math.min(product.stock, quantity);
|
||||
}
|
||||
}
|
||||
const cart = getCart(req);
|
||||
const current = cart[productId] || 0;
|
||||
cart[productId] = Math.min(product.stock, current + quantity);
|
||||
|
||||
res.redirect('/cart');
|
||||
});
|
||||
res.redirect(req.body.redirect || '/cart');
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/cart/update',
|
||||
asyncHandler(async (req, res) => {
|
||||
const cart = getCart(req);
|
||||
const updates = req.body.items || {};
|
||||
|
||||
for (const [id, qty] of Object.entries(updates)) {
|
||||
const productId = parseInt(id, 10);
|
||||
const quantity = parseInt(qty, 10);
|
||||
if (!productId) continue;
|
||||
|
||||
if (!quantity || quantity <= 0) {
|
||||
delete cart[productId];
|
||||
continue;
|
||||
}
|
||||
|
||||
const { rows } = await query('SELECT stock FROM products WHERE id = $1', [
|
||||
productId,
|
||||
]);
|
||||
if (rows[0]) {
|
||||
cart[productId] = Math.min(rows[0].stock, quantity);
|
||||
}
|
||||
}
|
||||
|
||||
res.redirect('/cart');
|
||||
})
|
||||
);
|
||||
|
||||
router.post('/cart/remove/:id', (req, res) => {
|
||||
const cart = getCart(req);
|
||||
@@ -137,131 +153,148 @@ router.post('/cart/remove/:id', (req, res) => {
|
||||
res.redirect('/cart');
|
||||
});
|
||||
|
||||
router.get('/checkout', requireAuth, (req, res) => {
|
||||
const cart = getCart(req);
|
||||
const items = cartItems(db, cart);
|
||||
if (items.length === 0) {
|
||||
return res.redirect('/cart');
|
||||
}
|
||||
router.get(
|
||||
'/checkout',
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const cart = getCart(req);
|
||||
const items = await cartItems(cart);
|
||||
if (items.length === 0) {
|
||||
return res.redirect('/cart');
|
||||
}
|
||||
|
||||
res.render('checkout', {
|
||||
title: 'Оформление заказа',
|
||||
items,
|
||||
total: cartTotal(items),
|
||||
error: null,
|
||||
});
|
||||
});
|
||||
|
||||
router.post('/checkout', requireAuth, (req, res) => {
|
||||
const cart = getCart(req);
|
||||
const items = cartItems(db, cart);
|
||||
if (items.length === 0) {
|
||||
return res.redirect('/cart');
|
||||
}
|
||||
|
||||
const { name, email, phone, address } = req.body;
|
||||
if (!name?.trim() || !email?.trim() || !address?.trim()) {
|
||||
return res.status(400).render('checkout', {
|
||||
res.render('checkout', {
|
||||
title: 'Оформление заказа',
|
||||
items,
|
||||
total: cartTotal(items),
|
||||
error: 'Заполните имя, email и адрес доставки',
|
||||
error: null,
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
const total = cartTotal(items);
|
||||
router.post(
|
||||
'/checkout',
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const cart = getCart(req);
|
||||
const items = await cartItems(cart);
|
||||
if (items.length === 0) {
|
||||
return res.redirect('/cart');
|
||||
}
|
||||
|
||||
const placeOrder = db.transaction(() => {
|
||||
for (const item of items) {
|
||||
const row = db
|
||||
.prepare('SELECT stock FROM products WHERE id = ?')
|
||||
.get(item.id);
|
||||
if (!row || row.stock < item.quantity) {
|
||||
throw new Error(`Недостаточно «${item.name}» на складе`);
|
||||
const { name, email, phone, address } = req.body;
|
||||
if (!name?.trim() || !email?.trim() || !address?.trim()) {
|
||||
return res.status(400).render('checkout', {
|
||||
title: 'Оформление заказа',
|
||||
items,
|
||||
total: cartTotal(items),
|
||||
error: 'Заполните имя, email и адрес доставки',
|
||||
});
|
||||
}
|
||||
|
||||
const total = cartTotal(items);
|
||||
const client = await pool.connect();
|
||||
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
|
||||
for (const item of items) {
|
||||
const { rows } = await client.query(
|
||||
'SELECT stock FROM products WHERE id = $1 FOR UPDATE',
|
||||
[item.id]
|
||||
);
|
||||
if (!rows[0] || rows[0].stock < item.quantity) {
|
||||
throw new Error(`Недостаточно «${item.name}» на складе`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const order = db
|
||||
.prepare(
|
||||
const orderResult = await client.query(
|
||||
`INSERT INTO orders (user_id, status, total_cents, customer_name, customer_email, customer_phone, address)
|
||||
VALUES (?, 'pending', ?, ?, ?, ?, ?)`
|
||||
)
|
||||
.run(
|
||||
req.session.userId,
|
||||
total,
|
||||
name.trim(),
|
||||
email.trim(),
|
||||
(phone || '').trim(),
|
||||
address.trim()
|
||||
VALUES ($1, 'pending', $2, $3, $4, $5, $6)
|
||||
RETURNING id`,
|
||||
[
|
||||
req.session.userId,
|
||||
total,
|
||||
name.trim(),
|
||||
email.trim(),
|
||||
(phone || '').trim(),
|
||||
address.trim(),
|
||||
]
|
||||
);
|
||||
const orderId = orderResult.rows[0].id;
|
||||
|
||||
const insertItem = db.prepare(
|
||||
`INSERT INTO order_items (order_id, product_id, quantity, price_cents)
|
||||
VALUES (?, ?, ?, ?)`
|
||||
);
|
||||
const updateStock = db.prepare(
|
||||
'UPDATE products SET stock = stock - ? WHERE id = ?'
|
||||
for (const item of items) {
|
||||
await client.query(
|
||||
`INSERT INTO order_items (order_id, product_id, quantity, price_cents)
|
||||
VALUES ($1, $2, $3, $4)`,
|
||||
[orderId, item.id, item.quantity, item.price_cents]
|
||||
);
|
||||
await client.query('UPDATE products SET stock = stock - $1 WHERE id = $2', [
|
||||
item.quantity,
|
||||
item.id,
|
||||
]);
|
||||
}
|
||||
|
||||
await client.query('COMMIT');
|
||||
req.session.cart = {};
|
||||
res.redirect(`/orders/${orderId}?success=1`);
|
||||
} catch (err) {
|
||||
await client.query('ROLLBACK');
|
||||
res.redirect(`/cart?error=${encodeURIComponent(err.message)}`);
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/orders',
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { rows: orders } = await query(
|
||||
`SELECT id, status, total_cents, created_at
|
||||
FROM orders WHERE user_id = $1
|
||||
ORDER BY created_at DESC`,
|
||||
[req.session.userId]
|
||||
);
|
||||
|
||||
for (const item of items) {
|
||||
insertItem.run(order.lastInsertRowid, item.id, item.quantity, item.price_cents);
|
||||
updateStock.run(item.quantity, item.id);
|
||||
res.render('orders', { title: 'Мои заказы', orders });
|
||||
})
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/orders/:id',
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { rows } = await query(
|
||||
'SELECT * FROM orders WHERE id = $1 AND user_id = $2',
|
||||
[req.params.id, req.session.userId]
|
||||
);
|
||||
const order = rows[0];
|
||||
|
||||
if (!order) {
|
||||
return res.status(404).render('error', {
|
||||
title: 'Не найдено',
|
||||
message: 'Заказ не найден',
|
||||
code: 404,
|
||||
});
|
||||
}
|
||||
|
||||
return order.lastInsertRowid;
|
||||
});
|
||||
|
||||
try {
|
||||
const orderId = placeOrder();
|
||||
req.session.cart = {};
|
||||
res.redirect(`/orders/${orderId}?success=1`);
|
||||
} catch (err) {
|
||||
res.redirect(`/cart?error=${encodeURIComponent(err.message)}`);
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/orders', requireAuth, (req, res) => {
|
||||
const orders = db
|
||||
.prepare(
|
||||
`SELECT id, status, total_cents, created_at
|
||||
FROM orders WHERE user_id = ?
|
||||
ORDER BY created_at DESC`
|
||||
)
|
||||
.all(req.session.userId);
|
||||
|
||||
res.render('orders', { title: 'Мои заказы', orders });
|
||||
});
|
||||
|
||||
router.get('/orders/:id', requireAuth, (req, res) => {
|
||||
const order = db
|
||||
.prepare(
|
||||
`SELECT * FROM orders WHERE id = ? AND user_id = ?`
|
||||
)
|
||||
.get(req.params.id, req.session.userId);
|
||||
|
||||
if (!order) {
|
||||
return res.status(404).render('error', {
|
||||
title: 'Не найдено',
|
||||
message: 'Заказ не найден',
|
||||
code: 404,
|
||||
});
|
||||
}
|
||||
|
||||
const items = db
|
||||
.prepare(
|
||||
const { rows: items } = await query(
|
||||
`SELECT oi.*, p.name, p.slug, p.image_url
|
||||
FROM order_items oi
|
||||
JOIN products p ON p.id = oi.product_id
|
||||
WHERE oi.order_id = ?`
|
||||
)
|
||||
.all(order.id);
|
||||
WHERE oi.order_id = $1`,
|
||||
[order.id]
|
||||
);
|
||||
|
||||
res.render('order', {
|
||||
title: `Заказ #${order.id}`,
|
||||
order,
|
||||
items,
|
||||
success: req.query.success === '1',
|
||||
});
|
||||
});
|
||||
res.render('order', {
|
||||
title: `Заказ #${order.id}`,
|
||||
order,
|
||||
items,
|
||||
success: req.query.success === '1',
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
Reference in New Issue
Block a user