-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
77 lines (63 loc) · 2.06 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import fs from 'node:fs/promises';
import bodyParser from 'body-parser';
import express from 'express';
const app = express();
app.use(bodyParser.json());
app.use(express.static('public'));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.get('/', async (req, res) => {
res.json("OK");
});
app.get('/meals', async (req, res) => {
const meals = await fs.readFile('./data/available-meals.json', 'utf8');
res.json(JSON.parse(meals));
});
app.post('/orders', async (req, res) => {
const orderData = req.body.order;
if (orderData === null || orderData.items === null || orderData.items.length === 0) {
return res
.status(400)
.json({ message: 'Missing data.' });
}
if (
orderData.customer.email === null ||
!orderData.customer.email.includes('@') ||
orderData.customer.name === null ||
orderData.customer.name.trim() === '' ||
orderData.customer.street === null ||
orderData.customer.street.trim() === '' ||
orderData.customer['postal-code'] === null ||
orderData.customer['postal-code'].trim() === '' ||
orderData.customer.city === null ||
orderData.customer.city.trim() === ''
) {
return res.status(400).json({
message:
'Missing data: Email, name, street, postal code or city is missing.',
});
}
const newOrder = {
...orderData,
id: (Math.random() * 1000).toString(),
};
const orders = await fs.readFile('./data/orders.json', 'utf8');
const allOrders = JSON.parse(orders);
allOrders.push(newOrder);
await fs.writeFile('./data/orders.json', JSON.stringify(allOrders));
res.status(201).json({ message: 'Order created!' });
});
app.use((req, res) => {
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
res.status(404).json({ message: 'Not found' });
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})