-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
69 lines (55 loc) · 1.35 KB
/
index.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
const app = require('express')();
const bodyParser = require('body-parser');
const { Post, Tag } = require('./models');
app.use(bodyParser.json());
app.get('/posts', async (req, res) => {
try {
const posts = await Post.findAll({
include: [
{
model: Tag,
as: 'tags',
through: { attributes: [] },
},
],
});
return res.status(200).json(posts);
} catch (err) {
return res.status(500).json({ err });
}
});
app.post('/posts', async (req, res) => {
try {
const { tags, ...data } = req.body;
const post = await Post.create(data);
if (tags && tags.length > 0) {
post.setTags(tags);
}
return res.status(200).json(post);
} catch (err) {
return res.status(500).json({ err });
}
});
app.put('/posts/:id', async (req, res) => {
try {
const { id } = req.params;
const post = await Post.findById(id);
const { tags, ...data } = req.body;
post.update(data);
if (tags && tags.length > 0) {
post.setTags(tags);
}
return res.status(200).json(post);
} catch (err) {
return res.status(500).json({ err });
}
});
app.post('/tags', async (req, res) => {
try {
const tag = await Tag.create(req.body);
return res.status(200).json(tag);
} catch (err) {
return res.status(500).json({ err });
}
});
app.listen(3000);