get/post requests

This commit is contained in:
2025-12-30 22:29:34 +03:00
parent bfde13afd0
commit ec65f155b2
2 changed files with 135 additions and 32 deletions

View File

@@ -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();
}
}
}

View File

@@ -1,8 +1,8 @@
import express from "express";
import randomUUID from "crypto";
import dotenv from "dotenv"
import DBAdapter from "./db/database.js";
import { error, timeStamp } from "console";
import { randomUUID } from "crypto";
import DBAdapter, { getCurrentDate, setCurrentDate } from "./db/database.js";
import { DB_INTERNAL_ERROR, DB_USER_ERROR } from "./db/database.js";
dotenv.config({
path: './server/.env'
@@ -27,15 +27,10 @@ const adapter = new DBAdapter({
dbUserPassword: PASSWORD
});
let currentDate = (new Date()).toISOString().slice(0, 10);
async function getCurrentDate() {
return currentDate;
}
function AddDays(dateString, days) {
let date = new Date(dateString);
date.setDate(date.getDate() + days);
return formatDate(date);
return date.toISOString().slice(0, 10);
}
function Random_Increase() {
@@ -74,13 +69,23 @@ app.get('/api/products', async(req, res) => {
app.post('/api/current-date/advance', async (req, res) => {
let currentDate = await getCurrentDate();
// TODO: select orders with current date and delete them from database
try {
const raw_ids = await adapter.getOrdersByDate(currentDate);
const ids = raw_ids.map(item => item.id);
await adapter.deleteOrdersByIds(ids);
// TODO: get all products and increase with Random_Increase()
let nextDate = AddDays(currentDate, 1);
currentDate = nextDate;
res.json({ currentDate: nextDate });
let nextDate = AddDays(currentDate, 1);
await setCurrentDate(nextDate);
res.json({ currentDate: nextDate });
} catch (err){
res.statusCode = 500;
res.message = "WHOOPS";
res.json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error : `${err}`
})
}
});
app.get('/api/orders', async(req, res) => {
@@ -120,28 +125,55 @@ app.get('/api/orders', async(req, res) => {
app.post('/api/orders', async (req, res) => {
let { customerName, orderDate } = req.body;
if (!customerName || !orderDate) {
return res.status(400).json({ message: 'Full name and date, please!' });
}
let currentDate = await getCurrentDate();
if (orderDate < currentDate) {
return res.status(400).json({ message: 'Date of order can\'t be more, than current!' });
}
let id = randomUUID();
// TODO: Insert id into orders
res.status(201).json({ id, customer_name: customerName, date: orderDate });
try {
await adapter.addOrder({
id,
customer_name: customerName,
orderDate
});
res.status(201).json({
id,
customerName,
orderDate
});
} catch (err) {
console.log('Error in POST /api/orders:', err);
switch(err.type) {
case DB_INTERNAL_ERROR:
res.status(500).json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error: err.error?.message || err.message
});
break;
case DB_USER_ERROR:
res.status(400).json({
timeStamp: new Date().toISOString(),
statusCode: 400,
error: err.error?.message || err.message
});
break;
default:
res.status(500).json({
timeStamp: new Date().toISOString(),
statusCode: 500,
message: "Unknown error",
error: err.message
});
}
}
});
app.use((req, res) => {
res.status(404).json({ error: 'Invalid route' });
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
app.listen(3000, async() => {
try {
await adapter.connect();