-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
68 lines (64 loc) · 2.17 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
const express = require('express');
const logging = require('morgan');
const errorHandler = require('errorhandler');
const bodyParser = require('body-parser');
const routes = require('./routes/index.js');
const { check, validationResult } = require('express-validator/check');
const app = express();
app.use(logging('dev'));
app.use(errorHandler());
app.use(bodyParser.json());
app.use((req, res, next) => {
if (req.headers.xauthor) return next();
return res.sendStatus(403);
});
app.get('/posts', (req, res) => {
return routes.posts.getPosts(req, res);
});
app.post('/posts',
[check('title').exists().isLength({ min: 1 }), check('content').exists().isLength({ min: 1 })],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.mapped() });
}
return routes.posts.addPost(req, res);
});
app.put('/posts/:postId',
[check('title').exists().isLength({ min: 1 }), check('content').exists().isLength({ min: 1 })],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.mapped() });
}
return routes.posts.updatePost(req, res);
});
app.delete('/posts/:postId', (req, res) => {
return routes.posts.removePost(req, res);
});
app.get('/posts/:postId/comments', (req, res) => {
return routes.comments.getComments(req, res);
});
app.post('/posts/:postId/comments',
[check('comment').exists().isLength({ min: 1 })],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.mapped() });
}
return routes.comments.addComment(req, res);
});
app.put('/posts/:postId/comments/:commentId',
[check('comment').exists().isLength({ min: 1 })],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.mapped() });
}
return routes.comments.updateComment(req, res);
});
app.delete('/posts/:postId/comments/:commentId', (req, res) => {
return routes.comments.removeComment(req, res);
});
console.log('Listening on http://localhost:3003');
app.listen(3003);