forked from japneetsingh0307/web422
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·84 lines (71 loc) · 2.18 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
const mongoDBConnectionString = "MongoDB Connection String Here";
const HTTP_PORT = process.env.PORT || 8080;
const express = require("express");
const bodyParser = require('body-parser');
const cors = require("cors");
const dataService = require("./modules/data-service.js");
const data = dataService(mongoDBConnectionString);
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.post("/api/posts", (req,res)=>{
data.addNewPost(req.body).then((msg)=>{
res.json({message: msg});
}).catch((err)=>{
res.json({message: `an error occurred: ${err}`});
});
});
// IMPORTANT NOTE: ?tag=#funny wll not function, but ?tag=funny will
app.get("/api/posts", (req,res) => {
data.getAllPosts(req.query.page, req.query.perPage, req.query.category, req.query.tag).then((data)=>{
res.json(data);
})
.catch((err)=>{
res.json({message: `an error occurred: ${err}`});
})
});
app.get("/api/categories", (req,res)=>{
data.getCategories().then((data)=>{
res.json(data);
})
.catch((err)=>{
res.json({message: `an error occurred: ${err}`});
})
});
app.get("/api/tags", (req,res)=>{
data.getTags().then((data)=>{
res.json(data);
})
.catch((err)=>{
res.json({message: `an error occurred: ${err}`});
})
});
app.get("/api/posts/:id",(req,res)=>{
data.getPostById(req.params.id).then(data=>{
res.json(data);
}).catch((err)=>{
res.json({message: `an error occurred: ${err}`});
});
});
app.put("/api/posts/:id", (req,res)=>{
data.updatePostById(req.body,req.params.id).then((msg)=>{
res.json({message: msg});
}).catch((err)=>{
res.json({message: `an error occurred: ${err}`});
});
});
app.delete("/api/posts/:id", (req,res)=>{
data.deletePostById(req.params.id).then((msg)=>{
res.json({message: msg});
}).catch((err)=>{
res.json({message: `an error occurred: ${err}`});
});
});
// Connect to the DB and start the server
data.connect().then(()=>{
app.listen(HTTP_PORT, ()=>{console.log("API listening on: " + HTTP_PORT)});
})
.catch((err)=>{
console.log("unable to start the server: " + err);
process.exit();
});