This repository has been archived by the owner on Jun 4, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharticles.js
191 lines (177 loc) · 5.28 KB
/
articles.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
const express = require("express");
const _ = require("lodash");
const Article = require("../models/article");
const User = require("../models/user");
const existenceVerifier = require("../helpers/existenceVerifier");
const DatabaseError = require("../errors/DatabaseError");
const verifyToken = require("../middlewares/verifyToken");
const router = express.Router();
/**
* GET
* 获得所有文章,可使用参数过滤。
* @param {String} sort 排序方式
* @param {Number} begin 分页用
* @param {Number} end 分页用
* @returns {JSON[]} 文章列表
*/
router.get("/", (req, res) => {
const begin = req.query.begin || 1;
const end = req.query.end || Number.MAX_SAFE_INTEGER;
const sort = req.query.sort || "descending";
let query;
query = Article.find({})
.sort({ createdAt: sort })
.skip(begin - 1)
.limit(end - begin + 1);
query.exec((err, articles) => {
if (err) {
res.status(500).send("500 Internal Server Error.");
} else {
const result = articles.map(n => {
let article = {};
article.id = n._id;
article.title = n.title;
article.content = n.content;
article.attachments = n.attachments;
article.tags = n.tags;
article.createdAt = n.createdAt;
article.createdBy = n.createdBy;
return article;
});
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.status(200).end(JSON.stringify(result));
}
});
});
/**
* GET
* 获得特定文章。
* @param {String} id 文章 ID
* @returns {JSON} 特定文章
*/
router.get("/:id", (req, res) => {
Article.findById(req.params.id, (err, article) => {
if (err) {
res.status(500).send("500 Internal Server Error.");
} else if (!article) {
res.status(404).send("404 Not Found: Article does not exist.");
} else {
let returnedArticle = {};
returnedArticle.id = article._id;
returnedArticle.title = article.title;
returnedArticle.content = article.content;
returnedArticle.attachments = article.attachments;
returnedArticle.tags = article.tags;
returnedArticle.createdAt = article.createdAt;
returnedArticle.createdBy = article.createdBy;
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.status(200).end(JSON.stringify(returnedArticle));
}
});
});
/**
* POST
* 新增文章。
* @param {Article} req.body
* @returns {String} Location header
*/
router.post("/", verifyToken, async (req, res) => {
try {
// 只有管理员能够发布文章。
if (!(await existenceVerifier(User, { _id: req.id, group: "admin" }))) {
return res
.status(401)
.send("401 Unauthorized: Insufficient permissions.");
}
} catch (e) {
if (e instanceof DatabaseError) {
return res.status(500).send("500 Internal Server Error.");
}
throw e;
}
req.body.createdBy = req.id;
req.createdAt = new Date().toISOString();
req.body.updatedBy = req.id;
req.updatedAt = req.createdAt;
const newArticle = new Article(req.body);
newArticle.save((err, article) => {
if (err) {
res.status(500).send("500 Internal Server Error.");
} else {
res.setHeader("Location", "/articles/" + article._id);
res.status(201).send("201 Created.");
}
});
});
/**
* PUT
* 更新文章。
* @param {String} id 需要更新的文章 ID
* @returns No Content 或 Not Found
*/
router.put("/:id", verifyToken, async (req, res) => {
let article;
try {
// 只有管理员能够更新文章。
if (!(await existenceVerifier(User, { _id: req.id, group: "admin" }))) {
return res
.status(401)
.send("401 Unauthorized: Insufficient permissions.");
}
article = await existenceVerifier(Article, {
_id: req.params.id
});
if (!article) {
return res.status(404).send("404 Not Found: Article does not exist.");
}
} catch (e) {
if (e instanceof DatabaseError) {
return res.status(500).send("500 Internal Server Error.");
}
throw e;
}
delete req.body.createdBy;
delete req.body.createdAt;
req.body.updatedAt = new Date().toISOString();
req.body.updatedBy = req.id;
_.merge(article, req.body);
Object.entries(req.body).forEach(([key]) => article.markModified(key));
article.save(err => {
if (err) {
res.status(500).send("500 Internal Server Error.");
} else {
res.status(204).send("204 No Content.");
}
});
});
/**
* DELETE
* 删除特定文章。
* @param {String} id 删除文章的 ID
* @returns No Content 或 Not Found
*/
router.delete("/:id", verifyToken, async (req, res) => {
try {
// 只有管理员能够删除文章。
if (!(await existenceVerifier(User, { _id: req.id, group: "admin" }))) {
return res
.status(401)
.send("401 Unauthorized: Insufficient permissions.");
}
} catch (e) {
if (e instanceof DatabaseError) {
return res.status(500).send("500 Internal Server Error.");
}
throw e;
}
Article.findByIdAndDelete(req.params.id, (err, article) => {
if (err) {
res.status(500).send("500 Internal Server Error.");
} else if (!article) {
res.status(404).send("404 Not Found: Article does not exist.");
} else {
res.status(204).send("204 No Content.");
}
});
});
module.exports = router;