168 lines
5.1 KiB
JavaScript
168 lines
5.1 KiB
JavaScript
import mdb from "mariadb"
|
|
|
|
export const DB_INTERNAL_ERROR = 'INTERNAL';
|
|
export const DB_USER_ERROR = 'USER';
|
|
|
|
let currentDate = (new Date()).toISOString().slice(0, 10);
|
|
|
|
export async function getCurrentDate() {
|
|
return currentDate;
|
|
}
|
|
|
|
export async function setCurrentDate(newDate) {
|
|
currentDate = newDate;
|
|
console.log(`📅 Date changed to: ${currentDate}`);
|
|
}
|
|
|
|
export default class DBAdapter {
|
|
#dbhost = 'localhost';
|
|
#dbPort = 3306;
|
|
#dbName = 'N';
|
|
#dbUserLogin = 'u';
|
|
#dbUserPassword = 'p';
|
|
#dbClient = null;
|
|
|
|
constructor({
|
|
dbHost,
|
|
dbPort,
|
|
dbName,
|
|
dbUserLogin,
|
|
dbUserPassword
|
|
}) {
|
|
this.#dbhost = dbHost;
|
|
this.#dbPort = dbPort;
|
|
this.#dbName = dbName;
|
|
this.#dbUserLogin = dbUserLogin;
|
|
this.#dbUserPassword = dbUserPassword;
|
|
this.#dbClient = new mdb.createPool({
|
|
host: this.#dbhost,
|
|
port: this.#dbPort,
|
|
database: this.#dbName,
|
|
user: this.#dbUserLogin,
|
|
password: this.#dbUserPassword,
|
|
dateStrings: true
|
|
});
|
|
}
|
|
|
|
async connect() {
|
|
try {
|
|
// Проверяем подключение, выполняя простой запрос
|
|
const conn = await this.#dbClient.getConnection();
|
|
console.log("✅ Database connection test successful");
|
|
conn.release();
|
|
} catch (err) {
|
|
console.error("❌ Database connection failed:", err.message);
|
|
// Пробрасываем ошибку дальше
|
|
return Promise.reject();
|
|
}
|
|
}
|
|
|
|
async disconnect() {
|
|
await this.#dbClient.end();
|
|
console.log("DISCONNECT");
|
|
}
|
|
|
|
async getProducts() {
|
|
try {
|
|
const products = await this.#dbClient.query('SELECT * FROM products ORDER BY name');
|
|
console.log("All products:", products);
|
|
return products;
|
|
} catch(err){
|
|
console.log(`WHOOPS`);
|
|
return Promise.reject();
|
|
}
|
|
}
|
|
|
|
async getOrders() {
|
|
try {
|
|
const raw_orders = await this.#dbClient.query('SELECT * FROM orders ORDER BY order_date ASC');
|
|
console.log("All orders:", raw_orders);
|
|
|
|
const items = await this.#dbClient.query(
|
|
`SELECT order_items.*, products.name AS product_name FROM order_items
|
|
JOIN products ON order_items.product_id = products.id`
|
|
);
|
|
console.log("All order items:", items);
|
|
|
|
const groupedItems = {};
|
|
if (items && items.length > 0) {
|
|
items.forEach(item => {
|
|
const orderId = item.order_id;
|
|
if (!groupedItems[orderId]) {
|
|
groupedItems[orderId] = [];
|
|
}
|
|
groupedItems[orderId].push(item);
|
|
});
|
|
}
|
|
|
|
const ordersWithItems = raw_orders.map(order => {
|
|
return {
|
|
...order,
|
|
items: groupedItems[order.id] || []
|
|
};
|
|
});
|
|
|
|
return ordersWithItems;
|
|
} catch(err) {
|
|
console.log(`WHOOPS: ${err.message}`);
|
|
return Promise.reject(err);
|
|
}
|
|
}
|
|
|
|
async addOrder({ id, customer_name, orderDate} ){
|
|
if (!customer_name || !orderDate){
|
|
return Promise.reject({
|
|
type: DB_USER_ERROR,
|
|
error: new Error("Empty in customer name or order date")
|
|
});
|
|
}
|
|
const currentDate = await getCurrentDate();
|
|
if (orderDate < currentDate){
|
|
return Promise.reject({
|
|
type: DB_USER_ERROR,
|
|
error: new Error("Invalid order date")
|
|
});
|
|
}
|
|
try {
|
|
await this.#dbClient.query('INSERT INTO orders (id, customer_name, order_date) VALUES (?, ?, ?)',
|
|
[id, customer_name, orderDate]
|
|
);
|
|
} catch(err){
|
|
return Promise.reject({
|
|
type: DB_INTERNAL_ERROR,
|
|
error: new Error("Server error")
|
|
});
|
|
}
|
|
}
|
|
|
|
async getOrdersByDate(date){
|
|
try {
|
|
const order_ids = await this.#dbClient.query('SELECT id FROM orders WHERE order_date = ?', [date]);
|
|
return order_ids;
|
|
} catch(err){
|
|
return Promise.reject();
|
|
}
|
|
}
|
|
|
|
async deleteOrdersByIds(orderIds) {
|
|
if (!orderIds || orderIds.length === 0) {
|
|
console.log("No orders to delete");
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const placeholders = orderIds.map(() => '?').join(',');
|
|
|
|
const result = await this.#dbClient.query(
|
|
`DELETE FROM orders WHERE id IN (${placeholders})`,
|
|
orderIds
|
|
);
|
|
|
|
console.log(`✅ Deleted ${result.affectedRows} orders with IDs:`, orderIds);
|
|
|
|
} catch(err) {
|
|
console.error(`❌ Error deleting orders:`, err.message);
|
|
return Promise.reject();
|
|
}
|
|
}
|
|
} |