-
Notifications
You must be signed in to change notification settings - Fork 1
/
routes.js
59 lines (50 loc) · 1.23 KB
/
routes.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
const express = require("express");
const Post = require("./models/Movie");
const router = express.Router();
router.get("/posts", async (req, res) => {
const posts = await Post.find();
res.send(posts);
});
router.post("/posts", async (req, res) => {
const post = new Post({
title: req.body.title,
content: req.body.content
});
await post.save();
res.send(post);
});
router.get("/posts/:id", async (req, res) => {
try {
const post = await Post.findOne({ _id: req.params.id });
res.send(post);
} catch {
res.status(404);
res.send({ error: "Post doesn't exist!" });
}
});
router.patch("/posts/:id", async (req, res) => {
try {
const post = await Post.findOne({ _id: req.params.id });
if (req.body.title) {
post.title = req.body.title;
}
if (req.body.content) {
post.content = req.body.content;
}
await post.save();
res.send(post);
} catch {
res.status(404);
res.send({ error: "Post doesn't exist!" });
}
});
router.delete("/posts/:id", async (req, res) => {
try {
await Post.deleteOne({ _id: req.params.id });
res.status(204).send();
} catch {
res.status(404);
res.send({ error: "Post doesn't exist!" });
}
});
module.exports = router;