-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorders.js
More file actions
124 lines (116 loc) · 3.25 KB
/
Copy pathorders.js
File metadata and controls
124 lines (116 loc) · 3.25 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
const mongoose = require('mongoose');
const Order = require("../model/order");
const Product = require("../model/product");
exports.orders_get_all = (req, res, next) => {
Order.find()
.populate('productId', 'name price')
.exec()
.then(docs => {
res.status(200).json({
orders : docs.map(doc => {
return {
productId : doc.productId,
quantity : doc.quantity,
_id : doc._id,
request : {
type : "GET",
url : "http://localhost:3000/orders/" + doc._id
}
}
})});
})
.catch(err => {
console.log(err);
res.status(500).json({
error : err
})
});
}
exports.orders_create_order = (req, res, next) => {
const order = new Order({
_id : mongoose.Types.ObjectId(),
productId : req.body.productId,
quantity : req.body.quantity
});
const productId = req.body.productId;
Product.findById(productId)
.exec()
.then(doc => {
if(!doc) {
return res.status(404).json({
message : "Product with the given productID not found",
});
}
order.save()
.then(result => {
res.status(201).json({
message : "Order added successfully",
productId : result.productId,
quantity : result.quantity,
request : {
type : "GET",
url : "http://localhost:3000/orders/" + result._id
}
});
})
.catch(err => {
res.status(500).json({
error : err
})
next(err);
});
})
.catch(err => {
res.status(500).json({
error : err,
message : "Product.find() catch triggered"
})
next(err);
});
}
exports.orders_get_order = (req, res, next) => {
const orderId = req.params.orderId;
Order.findById(orderId)
.populate('productId', 'name price')
.exec()
.then(order => {
if(!order) {
return res.status(404).json({
message : "Order with the given ID not found"
});
}
res.status(200).json({
message : "Order details",
productId : order.productId,
quantity : order.quantity,
orderId : order._id,
request : {
type : "GET",
description: "get all the orders",
url : "http://localhost:3000/orders"
}
})
})
.catch(err => {
console.log(err);
res.status(500).json({
error : err
});
});
}
exports.orders_delete_order = (req, res, next) => {
const orderId = req.params.orderId;
Order.remove({_id : orderId})
.exec()
.then(result => {
res.status(200).json({
message : "Order was deleted",
result : result
});
})
.catch(err => {
res.status(500).json({
error : err
});
});
}