get/post requests
This commit is contained in:
@@ -1,5 +1,19 @@
|
||||
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;
|
||||
@@ -25,7 +39,8 @@ export default class DBAdapter {
|
||||
port: this.#dbPort,
|
||||
database: this.#dbName,
|
||||
user: this.#dbUserLogin,
|
||||
password: this.#dbUserPassword
|
||||
password: this.#dbUserPassword,
|
||||
dateStrings: true
|
||||
});
|
||||
}
|
||||
|
||||
@@ -87,11 +102,67 @@ export default class DBAdapter {
|
||||
};
|
||||
});
|
||||
|
||||
console.log("Orders with items:", ordersWithItems);
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user