forked from Alexey/DAS_2024_1
82 lines
2.1 KiB
JavaScript
82 lines
2.1 KiB
JavaScript
|
import express from 'express';
|
||
|
import { JsonDB, Config } from 'node-json-db';
|
||
|
|
||
|
const app = express();
|
||
|
|
||
|
const db = new JsonDB(new Config("db", true, true, '/'));
|
||
|
const port = process.env.PORT || 4000;
|
||
|
|
||
|
app.use(express.json());
|
||
|
|
||
|
// CORS settings
|
||
|
app.use((req, res, next) => {
|
||
|
res.setHeader('Access-Control-Allow-Origin', '*');
|
||
|
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
|
||
|
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
|
||
|
next();
|
||
|
});
|
||
|
|
||
|
// Get all
|
||
|
app.get('/waiters', async (req, res) => {
|
||
|
res.send(await db.getData('/waiters'));
|
||
|
});
|
||
|
|
||
|
// Create one
|
||
|
app.post('/waiters', async (req, res) => {
|
||
|
let newWaiter = req.body;
|
||
|
// Generate id
|
||
|
newWaiter.id = crypto.randomUUID();
|
||
|
await db.push("/waiters/" + newWaiter.id, newWaiter);
|
||
|
res.send(newWaiter);
|
||
|
});
|
||
|
|
||
|
// Get one
|
||
|
app.get('/waiters/:id', async (req, res) => {
|
||
|
const id = req.params.id;
|
||
|
const waiter = await db.getData('/waiters/' + id);
|
||
|
if (!waiter) {
|
||
|
res.status(404).json({ message: 'Waiter not found' });
|
||
|
return;
|
||
|
}
|
||
|
res.send(waiter);
|
||
|
});
|
||
|
|
||
|
// Get all for one restaurant
|
||
|
app.get('/waiters/from-restaurant/:id', async (req, res) => {
|
||
|
const restaurantId = req.params.id;
|
||
|
const waiters = await db.filter('/waiters', w => w.restaurant_id === restaurantId);
|
||
|
res.send(waiters ?? []);
|
||
|
});
|
||
|
|
||
|
// Update one
|
||
|
app.put('/waiters/:id', async (req, res) => {
|
||
|
const id = req.params.id;
|
||
|
const updatedWaiter = req.body;
|
||
|
const waiterExists = await db.exists('/waiters/' + id);
|
||
|
|
||
|
if (!waiterExists) {
|
||
|
res.status(404).json({ message: 'Waiter not found' });
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
updatedWaiter.id = id;
|
||
|
|
||
|
await db.push('/waiters/' + id, updatedWaiter, true);
|
||
|
res.send(updatedWaiter);
|
||
|
});
|
||
|
|
||
|
// Delete one
|
||
|
app.delete('/waiters/:id', async (req, res) => {
|
||
|
const id = req.params.id;
|
||
|
const waiterExists = await db.exists('/waiters/' + id);
|
||
|
|
||
|
if (!waiterExists) {
|
||
|
res.status(404).json({ message: 'Waiter not found' });
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
await db.delete('/waiters/' + id);
|
||
|
res.status(200);
|
||
|
});
|
||
|
|
||
|
app.listen(port)
|