-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
98 lines (84 loc) · 2.47 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
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
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const data = require('./data');
const app = express();
app.use(bodyParser.json());
app.use(cors());
const PORT = process.env.PORT || 9000;
const PAGNATION_UNIT = 10;
const {
users,
loginMsgs,
articleMsgs,
articles,
comments,
commentMsgs
} = data;
app.get('/', (req, res) => {
res.send('Server is working')
});
app.post('/login', (req, res) => {
const userData = req.body;
if (!userData.id || !userData.password) {
res.status(400).json(loginMsgs.invalid.msg);
}
else if (users[userData.id] !== undefined && userData.password === users[userData.id].password) {
res.json(loginMsgs.success.msg);
}
else {
res.status(400).json(loginMsgs.fail.msg);
}
});
app.route('/article')
.get((req, res) => {
const page = req.query.page === undefined ? 1 : parseInt(req.query.page);
const arr = [];
const keys = Object.keys(articles).map(e => parseInt(e)).sort((a, b) => a - b);
let pointer = keys[keys.length - 1] - (page - 1) * PAGNATION_UNIT;
let count = 0;
while (count < PAGNATION_UNIT) {
if (pointer <= 0) break;
if (articles[pointer] === undefined) {
pointer--;
continue;
}
let article = {
no: pointer,
title: articles[pointer].title,
img: 'https://img.youtube.com/vi/' + articles[pointer].videoId + '/0.jpg',
author: users[articles[pointer].authorId].nickname,
datetime: articles[pointer].datetime
}
pointer--;
arr.push(article);
count++;
}
res.json(arr);
});
app.get('/article/:no', (req, res) => {
if (!Number.isInteger(parseInt(req.params.no))) {
res.status(400).json(articleMsgs.notNumber.msg);
return;
}
const no = parseInt(req.params.no);
if (articles[no] === undefined) {
res.status(404).json(articleMsgs.notExist.msg);
}
else {
res.json(articles[no]);
}
})
app.get('/comment/:no', (req, res) => {
if (!Number.isInteger(parseInt(req.params.no))) {
res.status(400).json(commentMsgs.invalidNo.msg);
return;
}
const no = parseInt(req.params.no);
res.json(
comments[no]
)
})
app.listen(PORT, () => {
console.log(`Listening... ${PORT}`);
});