Files
DELIVER_MAN/server/server.js

162 lines
4.2 KiB
JavaScript

import express from "express";
import randomUUID from "crypto";
import dotenv from "dotenv"
import DBAdapter from "./db/database.js";
import { error, timeStamp } from "console";
dotenv.config({
path: './server/.env'
});
const {
HOST,
PORT,
DATABASE,
USER,
PASSWORD
} = process.env;
const app = express();
app.use(express.json());
const adapter = new DBAdapter({
dbHost: HOST,
dbPort: PORT,
dbName: DATABASE,
dbUserLogin: USER,
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);
}
function Random_Increase() {
return Math.floor(Math.random() * 5) + 1;
}
app.get('/api/current-date', async (req, res) => {
let currentDate = await getCurrentDate();
res.json({ currentDate });
});
app.get('/api/products', async(req, res) => {
try {
const db_products = await adapter.getProducts();
const products = db_products.map(
( {id, name, quantity} ) => ({
ID: id,
pr_name: name,
count: quantity
})
);
res.statusCode = 200;
res.message = "OK";
res.json(products);
} catch (err){
res.statusCode = 500;
res.message = "WHOOPS";
res.json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error : `${err}`
})
}
});
app.post('/api/current-date/advance', async (req, res) => {
let currentDate = await getCurrentDate();
// TODO: select orders with current date and delete them from database
// TODO: get all products and increase with Random_Increase()
let nextDate = AddDays(currentDate, 1);
currentDate = nextDate;
res.json({ currentDate: nextDate });
});
app.get('/api/orders', async(req, res) => {
try {
const db_orders = await adapter.getOrders();
const orders = db_orders.map(
( {id, customer_name, order_date, status, total_amount, items} ) => ({
ID: id,
customer: customer_name,
date: order_date,
status: status,
total: total_amount,
items: items ? items.map(item => ({
product_id: item.product_id,
product_name: item.product_name || item.name,
quantity: item.quantity,
price: item.price
})) : []
})
);
res.statusCode = 200;
res.message = "OK";
res.json(orders);
} catch (err) {
res.statusCode = 500;
res.message = "WHOOPS";
res.json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error: `${err}`
});
}
});
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 });
});
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();
console.log(`✅ Server running on port 3000`);
console.log(`📡 Local: http://localhost:3000`);
} catch(err){
console.log("Shutting down application...");
process.exit(100);
}
});
process.on('SIGTERM', () => {
console.log("CLOSE APP");
app.close( async() => {
await adapter.disconnect();
console.log("DB DISCONNECTED");
});
});