191 lines
5.5 KiB
TypeScript
191 lines
5.5 KiB
TypeScript
import Cookies from 'js-cookie';
|
||
|
||
export interface CartItem {
|
||
id: number;
|
||
title: string;
|
||
price: number;
|
||
quantity: number;
|
||
}
|
||
|
||
interface Cart {
|
||
cart_items: CartItem[];
|
||
}
|
||
|
||
// Save cart to cookies
|
||
export const saveCart = (cartItems: CartItem[]): void => {
|
||
const cart: Cart = {
|
||
cart_items: cartItems
|
||
};
|
||
const cartData = JSON.stringify(cart);
|
||
Cookies.set('cart', cartData, { expires: 7 });
|
||
};
|
||
|
||
// Get cart from cookies
|
||
export const getCart = (): CartItem[] => {
|
||
const cartData = Cookies.get('cart');
|
||
if (!cartData) return [];
|
||
|
||
const cart: Cart = JSON.parse(cartData);
|
||
return cart.cart_items;
|
||
};
|
||
|
||
// Clear cart in cookies
|
||
export const clearCart = (): void => {
|
||
Cookies.remove('cart');
|
||
};
|
||
|
||
|
||
/*
|
||
import Cookies from 'js-cookie';
|
||
import axios from 'axios';
|
||
|
||
export interface CartItem {
|
||
id: number;
|
||
title: string;
|
||
price: number;
|
||
quantity: number;
|
||
}
|
||
|
||
// Сохранить корзину в cookies
|
||
export const saveCart = (cartItems: CartItem[]): void => {
|
||
const cartData = JSON.stringify(cartItems);
|
||
Cookies.set('cart', cartData, { expires: 7 }); // Срок хранения cookies 7 дней
|
||
};
|
||
|
||
// Получить корзину из cookies
|
||
export const getCart = (): CartItem[] => {
|
||
const cartData = Cookies.get('cart');
|
||
return cartData ? JSON.parse(cartData) : []; // Возвращаем пустой массив, если корзина не найдена
|
||
};
|
||
|
||
// Очистить корзину в cookies
|
||
export const clearCart = (): void => {
|
||
Cookies.remove('cart'); // Удаляем cookies с данными корзины
|
||
};
|
||
|
||
// Отправить данные корзины на сервер
|
||
export const sendOrderToServer = async (userId: number): Promise<void> => {
|
||
try {
|
||
const cartItems = getCart(); // Получаем текущую корзину из cookies
|
||
|
||
if (cartItems.length === 0) {
|
||
console.warn('Корзина пуста, нечего отправлять');
|
||
return;
|
||
}
|
||
|
||
// Данные для отправки
|
||
const orderData = {
|
||
userId, // ID пользователя
|
||
items: cartItems, // Товары из корзины
|
||
orderDate: new Date().toISOString(), // Текущая дата
|
||
};
|
||
|
||
// Отправляем запрос на сервер
|
||
const response = await axios.post('/api/orders', orderData);
|
||
|
||
if (response.status === 200) {
|
||
console.log('Заказ успешно отправлен!');
|
||
clearCart(); // Очищаем корзину после успешного заказа
|
||
} else {
|
||
console.error('Ошибка при отправке заказа:', response.statusText);
|
||
}
|
||
} catch (error) {
|
||
console.error('Произошла ошибка при отправке заказа:', error);
|
||
}
|
||
};
|
||
|
||
|
||
// Херня для отправки на БД
|
||
// Вид БД должен быть таким:
|
||
// CREATE TABLE orders (
|
||
// id SERIAL PRIMARY KEY,
|
||
// user_id INT NOT NULL,
|
||
// order_date TIMESTAMP NOT NULL
|
||
// );
|
||
|
||
// CREATE TABLE order_items (
|
||
// id SERIAL PRIMARY KEY,
|
||
// order_id INT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
|
||
// product_id INT NOT NULL,
|
||
// title TEXT NOT NULL,
|
||
// price NUMERIC(10, 2) NOT NULL,
|
||
// quantity INT NOT NULL
|
||
// );
|
||
|
||
|
||
const express = require('express');
|
||
const { Pool } = require('pg');
|
||
|
||
const app = express();
|
||
const port = 3000;
|
||
|
||
// Настройка подключения к PostgreSQL
|
||
const pool = new Pool({
|
||
user: 'your_user', // Замените на пользователя PostgreSQL
|
||
host: 'localhost', // Хост базы данных
|
||
database: 'your_database', // Название базы данных
|
||
password: 'your_password', // Пароль пользователя PostgreSQL
|
||
port: 5432, // Порт PostgreSQL (по умолчанию 5432)
|
||
});
|
||
|
||
// Middleware для обработки JSON
|
||
app.use(express.json());
|
||
|
||
// Маршрут для обработки POST-запросов на '/api/orders'
|
||
app.post('/api/orders', async (req, res) => {
|
||
const { userId, items, orderDate } = req.body;
|
||
|
||
// Проверка данных
|
||
if (!userId || !items || items.length === 0) {
|
||
return res.status(400).json({ error: 'Invalid request. Missing userId or items.' });
|
||
}
|
||
|
||
const client = await pool.connect();
|
||
|
||
try {
|
||
// Начало транзакции
|
||
await client.query('BEGIN');
|
||
|
||
// Вставка заказа в таблицу orders
|
||
const orderResult = await client.query(
|
||
`INSERT INTO orders (user_id, order_date) VALUES ($1, $2) RETURNING id`,
|
||
[userId, orderDate || new Date()]
|
||
);
|
||
|
||
const orderId = orderResult.rows[0].id;
|
||
|
||
// Вставка позиций заказа в таблицу order_items
|
||
const insertItemQuery = `
|
||
INSERT INTO order_items (order_id, product_id, title, price, quantity)
|
||
VALUES ($1, $2, $3, $4, $5)
|
||
`;
|
||
|
||
for (const item of items) {
|
||
await client.query(insertItemQuery, [
|
||
orderId,
|
||
item.id,
|
||
item.title,
|
||
item.price,
|
||
item.quantity,
|
||
]);
|
||
}
|
||
|
||
// Завершение транзакции
|
||
await client.query('COMMIT');
|
||
|
||
res.status(201).json({ message: 'Order created successfully', orderId });
|
||
} catch (error) {
|
||
// Откат транзакции в случае ошибки
|
||
await client.query('ROLLBACK');
|
||
console.error('Error creating order:', error);
|
||
res.status(500).json({ error: 'Failed to create order' });
|
||
} finally {
|
||
client.release();
|
||
}
|
||
});
|
||
|
||
// Запуск сервера
|
||
app.listen(port, () => {
|
||
console.log(`Server is running on http://localhost:${port}`);
|
||
});
|
||
*/ |