get/post requests
This commit is contained in:
@@ -1,5 +1,19 @@
|
|||||||
import mdb from "mariadb"
|
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 {
|
export default class DBAdapter {
|
||||||
#dbhost = 'localhost';
|
#dbhost = 'localhost';
|
||||||
#dbPort = 3306;
|
#dbPort = 3306;
|
||||||
@@ -25,7 +39,8 @@ export default class DBAdapter {
|
|||||||
port: this.#dbPort,
|
port: this.#dbPort,
|
||||||
database: this.#dbName,
|
database: this.#dbName,
|
||||||
user: this.#dbUserLogin,
|
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;
|
return ordersWithItems;
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
console.log(`WHOOPS: ${err.message}`);
|
console.log(`WHOOPS: ${err.message}`);
|
||||||
return Promise.reject(err);
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import express from "express";
|
import express from "express";
|
||||||
import randomUUID from "crypto";
|
|
||||||
import dotenv from "dotenv"
|
import dotenv from "dotenv"
|
||||||
import DBAdapter from "./db/database.js";
|
import { randomUUID } from "crypto";
|
||||||
import { error, timeStamp } from "console";
|
import DBAdapter, { getCurrentDate, setCurrentDate } from "./db/database.js";
|
||||||
|
import { DB_INTERNAL_ERROR, DB_USER_ERROR } from "./db/database.js";
|
||||||
|
|
||||||
dotenv.config({
|
dotenv.config({
|
||||||
path: './server/.env'
|
path: './server/.env'
|
||||||
@@ -27,15 +27,10 @@ const adapter = new DBAdapter({
|
|||||||
dbUserPassword: PASSWORD
|
dbUserPassword: PASSWORD
|
||||||
});
|
});
|
||||||
|
|
||||||
let currentDate = (new Date()).toISOString().slice(0, 10);
|
|
||||||
|
|
||||||
async function getCurrentDate() {
|
|
||||||
return currentDate;
|
|
||||||
}
|
|
||||||
function AddDays(dateString, days) {
|
function AddDays(dateString, days) {
|
||||||
let date = new Date(dateString);
|
let date = new Date(dateString);
|
||||||
date.setDate(date.getDate() + days);
|
date.setDate(date.getDate() + days);
|
||||||
return formatDate(date);
|
return date.toISOString().slice(0, 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
function Random_Increase() {
|
function Random_Increase() {
|
||||||
@@ -74,13 +69,23 @@ app.get('/api/products', async(req, res) => {
|
|||||||
|
|
||||||
app.post('/api/current-date/advance', async (req, res) => {
|
app.post('/api/current-date/advance', async (req, res) => {
|
||||||
let currentDate = await getCurrentDate();
|
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);
|
||||||
|
await setCurrentDate(nextDate);
|
||||||
let nextDate = AddDays(currentDate, 1);
|
res.json({ currentDate: nextDate });
|
||||||
currentDate = nextDate;
|
} catch (err){
|
||||||
res.json({ currentDate: nextDate });
|
res.statusCode = 500;
|
||||||
|
res.message = "WHOOPS";
|
||||||
|
res.json({
|
||||||
|
timeStamp: new Date().toISOString(),
|
||||||
|
statusCode: 500,
|
||||||
|
error : `${err}`
|
||||||
|
})
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
app.get('/api/orders', async(req, res) => {
|
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) => {
|
app.post('/api/orders', async (req, res) => {
|
||||||
let { customerName, orderDate } = req.body;
|
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();
|
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) => {
|
app.use((req, res) => {
|
||||||
res.status(404).json({ error: 'Invalid route' });
|
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() => {
|
app.listen(3000, async() => {
|
||||||
try {
|
try {
|
||||||
await adapter.connect();
|
await adapter.connect();
|
||||||
|
|||||||
Reference in New Issue
Block a user