-
Notifications
You must be signed in to change notification settings - Fork 0
/
viewRouter.js
107 lines (92 loc) · 2.55 KB
/
viewRouter.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
96
97
98
99
100
101
102
103
104
105
106
107
const express = require('express')
const mongo = require('mongodb')
let router = express.Router();
router.get("/", loadInventory)
router.get("/:id", getItem)
router.put("/csv", exportCSV)
router.post("/delete/:id", deleteItem)
router.post("/edit/:id", updateItem)
function exportCSV(req,res,next){
req.app.locals.db.collection("items").find({}).toArray(function(err,result){
if(err){
res.status(500).send("Error reading database");
console.log(err);
return;
}
res.status(200).send(JSON.stringify(result));
return;
})
}
function loadInventory(req,res,next){
let data = req.query.name;
let query = {};
if(req.query.name === undefined){
query = {};
}else{
query = {name:new RegExp(data,"i")}
}
console.log(query);
req.app.locals.db.collection("items").find(query).toArray(function(err,result){
if(err){
res.status(500).send("Error reading database");
console.log(err);
return;
}
res.items = result;
res.render("pages/viewInventory",{items:result});
return;
})
}
function getItem(req,res,next){
let id = req.params.id;
try{
id = new mongo.ObjectId(req.params.id);
}catch{
res.status(404).send("Invalid ID");
return
}
const promise = req.app.locals.db.collection("items").findOne({_id:Object(id)});
promise.then((result)=>{
if(result === null){
res.status(404).send("cannot find item");
}else{
let string = JSON.stringify(result)
res.render("pages/item" , {item:result,data:string})
}
})
}
function deleteItem(req,res,next){
let id = req.params.id;
try{
id = new mongo.ObjectId(req.params.id);
}catch{
res.status(404).send("Invalid ID");
return
}
req.app.locals.db.collection("items").deleteOne({_id:Object(id)}, function(err,result){
if (err){
res.status(404).send("error removing to database");
return
}
res.status(200).send();
});
}
function updateItem(req,res,next){
let id = req.params.id;
let data = req.body;
try{
id = new mongo.ObjectId(req.params.id);
}catch{
res.status(404).send("Invalid ID");
return
}
console.log(req.body)
req.app.locals.db.collection("items").updateOne({_id:Object(id)},{$set:{name:data.name, cost:data.cost, numItems: data.numItems}}, function(err,result){
if (err){
res.status(404).send("error updating database");
return
};
res.status(200).send(JSON.stringify(data));
})
}
module.exports = router;