forked from daniel-alts/pizza_app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
95 lines (65 loc) · 2.06 KB
/
index.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const express = require('express');
const moment = require('moment');
const mongoose = require('mongoose');
const orderModel = require('./orderModel');
const PORT = 3334
const app = express()
app.use(express.json());
app.get('/', (req, res) => {
return res.json({ status: true })
})
app.post('/order', async (req, res) => {
const body = req.body;
const total_price = body.items.reduce((prev, curr) => {
prev += curr.price
return prev
}, 0);
const order = await orderModel.create({
items: body.items,
created_at: moment().toDate(),
total_price
})
return res.json({ status: true, order })
})
app.get('/order/:orderId', async (req, res) => {
const { orderId } = req.params;
const order = await orderModel.findById(orderId)
if (!order) {
return res.status(404).json({ status: false, order: null })
}
return res.json({ status: true, order })
})
app.get('/orders', async (req, res) => {
const orders = await orderModel.find()
return res.json({ status: true, orders })
})
app.patch('/order/:id', async (req, res) => {
const { id } = req.params;
const { state } = req.body;
const order = await orderModel.findById(id)
if (!order) {
return res.status(404).json({ status: false, order: null })
}
if (state < order.state) {
return res.status(422).json({ status: false, order: null, message: 'Invalid operation' })
}
order.state = state;
await order.save()
return res.json({ status: true, order })
})
app.delete('/order/:id', async (req, res) => {
const { id } = req.params;
const order = await orderModel.deleteOne({ _id: id})
return res.json({ status: true, order })
})
mongoose.connect('mongodb://localhost:27017')
mongoose.connection.on("connected", () => {
console.log("Connected to MongoDB Successfully");
});
mongoose.connection.on("error", (err) => {
console.log("An error occurred while connecting to MongoDB");
console.log(err);
});
app.listen(PORT, () => {
console.log('Listening on port, ', PORT)
})