-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
105 lines (93 loc) · 2.53 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 app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/blogfall2017', {
useMongoClient: true,
});
var PostSchema = mongoose.Schema({
title: {type: String, required: true},
body: String,
tag: {type: String, enum: ['POLITICS','ECONOMY','EDUCATION']},
posted: {type: Date, default: Date.now}
}, {collection: 'post'});
var PostModel = mongoose.model("PostModel", PostSchema);
//GET /style.css etc
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json()); //for parsing application/json
app.use(bodyParser.urlencoded({extended: true}));//for parsing application/x-www-form-urlencoded
app.post("/api/blogpost", createPost);
app.get("/api/blogpost", getAllPosts);
app.get("/api/blogpost/:id", getPostById);
app.delete("/api/blogpost/:id", deletePost);
app.put("/api/blogpost/:id", updatePost);
function updatePost(req, res){
var postId = req.params.id;
var post = req.body;
PostModel
.update({_id: postId}),{
title: post.title,
body: post.body
})
.then(
function(status){
res.sendStatus(200);
},
function(err){
res.sendStatus(400);
}
);
}
function getPostById(req, res){
var postId = req.params.id;
PostModel
.findById(postId)
.then(
function (post){
res.json(post);
},
function (err){
res.sendStatus(400);
}
);
}
function deletePost(req, res) {
var postId = req.params.id;
PostModel
.remove({_id: postId});
then(
function (status) {
res.sendStatus(200);
},
function () {
res.sendStatus(400);
}
);
}
function getAllPosts(req, res) {
PostModel
.find()
.then(
function (posts) {
res.json(posts);
},
function (err) {
res.sendStatus(400);
}
);
}
function createPost (req,res){
var post = req.body;
console.log(post);
PostModel
.create(post)
.then(
function(postObj) {
res.json(200);
},
function (error) {
res.sendStatus(400);
}
);
}
app.listen(3000);