-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
105 lines (88 loc) · 2.05 KB
/
server.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
var express = require("express");
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var config = require("./config");
var Item = require("./models/item");
var app = express();
app.use(bodyParser.json());
app.use(express.static("public"));
app.get("/items", function(req, res) {
Item.find(function(err, items) {
if (err) {
return res.status(500).json({
message: "Internal Server Error"
});
}
res.json(items);
});
});
app.post("/items", function(req, res) {
Item.create({
name: req.body.name
}, function(err, item) {
if (err) {
return res.status(500).json({
message: "Internal Server Error"
});
}
res.status(201).json(item);
});
});
app.put("/items/:id", function(req, res) {
Item.findOneAndUpdate({id: req.params.id}, {name: req.body.name},
function(err, item) {
if (err) {
return res.status(500).json({
message: "Internal Server Error"
});
}
res.status(200).json(item);
}
);
});
app.delete("/items/:id", function(req, res) {
if (!req.body) {
return res.status(400).json({
message: "Invalid body"
});
}
Item.findOneAndRemove({
id: req.params.id
}, function(err, item) {
if (err) {
return res.status(500).json({
message: "Internal Server Error"
});
}
res.status(200).json(item); //storage.items
}
);
});
app.use("*", function(req, res) {
res.status(404).json({
message: "Not Found"
});
});
var runServer = function(callback) {
mongoose.connect(config.DATABASE_URL, function(err) {
if (err && callback) {
return callback(err);
}
app.listen(config.PORT, function() {
console.log("Listening on localhost:" + config.PORT);
if (callback) {
callback();
}
});
});
};
// Make this file both an executable script and a module.
if (require.main === module) {
runServer(function(err) {
if (err) {
console.error(err);
}
});
};
exports.app = app;
exports.runServer = runServer;