/
post.controller.js
380 lines (364 loc) · 10.2 KB
/
post.controller.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/**
* Post Controller
*/
import Joi from 'joi';
import HTTPStatus from 'http-status';
import contants from '../config/constants';
import { filteredBody } from '../utils/filteredBody';
import Post from '../models/post.model';
import User from '../models/user.model';
export const validation = {
create: {
body: {
title: Joi.string()
.min(3)
.required(),
text: Joi.string().required(),
},
},
update: {
body: {
title: Joi.string().min(3),
text: Joi.string(),
},
},
};
/**
* @api {get} /posts Get posts
* @apiDescription Get a list of posts
* @apiName getListOfPost
* @apiGroup Post
*
* @apiHeader {Authorization} Authorization JWT Token
*
* @apiParam (query) {Int} skip Number of skip posts
* @apiParam (query) {Int} limit Maximum number of posts
*
* @apiSuccess {Number} status Status of the Request.
* @apiSuccess {Object[]} post Post list.
* @apiSuccess {String} post._id Post _id.
* @apiSuccess {String} post.title Post title.
* @apiSuccess {String} post.text Post text.
* @apiSuccess {Object} post.author Post author.
* @apiSuccess {String} post.author._id Post author _id.
* @apiSuccess {String} post.author.username Post author username.
* @apiSuccess {String} post.createdAt Post created date.
*
*
* @apiParam (Login) {String} pass Only logged in users can do this.
*
* @apiHeaderExample {json} Header-Example:
* {
* "AUTHORIZATION": "JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1OTBhMWI3ODAzMDI3N2NiNjQxM2JhZGUiLCJpYXQiOjE0OTM4MzQ2MTZ9.RSlMF6RRwAALZQRdfKrOZWnuHBk-mQNnRcCLJsc8zio"
* }
*
* @apiSuccessExample Success-Response:
*
* HTTP/1.1 200 OK
*
* [
* {
* _id: '123',
* title: 'New title 1',
* text: 'New text 1',
* createdAt: '2017-05-03',
* author: {
* _id: '123312',
* username: 'Jon'
* }
* },
* {
* _id: '12234',
* title: 'New title 2',
* text: 'New text 2',
* createdAt: '2017-05-03',
* author: {
* _id: '123312234',
* username: 'Jon'
* }
* }
* ]
*
* @apiErrorExample {json} Post not found
* HTTP/1.1 404 Not Found
* @apiErrorExample {json} Unauthorized
* HTTP/1.1 401 Unauthorized
*/
export async function getList(req, res, next) {
try {
const promise = await Promise.all([
User.findById(req.user._id),
Post.list({ skip: req.query.skip, limit: req.query.limit }),
]);
const postsWithFavorite = promise[1].reduce((arr, post) => {
const favorite = promise[0]._favorites.isPostIsFavorite(post._id);
arr.push({
...post.toJSON(),
favorite,
});
return arr;
}, []);
return res.status(HTTPStatus.OK).json(postsWithFavorite);
} catch (err) {
err.status = HTTPStatus.BAD_REQUEST;
return next(err);
}
}
/**
* @api {get} /posts/:id Get a single post
* @apiDescription Get a single post
* @apiName getPost
* @apiGroup Post
*
* @apiHeader {Authorization} Authorization JWT Token
*
* @apiSuccess {Number} status Status of the Request.
* @apiSuccess {Object} post Post created.
* @apiSuccess {String} post._id Post _id.
* @apiSuccess {String} post.title Post title.
* @apiSuccess {String} post.text Post text.
* @apiSuccess {Object} post.author Post author.
* @apiSuccess {String} post.author._id Author id.
* @apiSuccess {String} post.author.username Author username.
* @apiSuccess {String} post.createdAt Post created date.
* @apiSuccess {Boolean} favorite User have favorite post
*
* @apiParam (Login) {String} pass Only logged in users can do this.
*
* @apiHeaderExample {json} Header-Example:
* {
* "AUTHORIZATION": "JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1OTBhMWI3ODAzMDI3N2NiNjQxM2JhZGUiLCJpYXQiOjE0OTM4MzQ2MTZ9.RSlMF6RRwAALZQRdfKrOZWnuHBk-mQNnRcCLJsc8zio"
* }
*
* @apiSuccessExample Success-Response:
*
* HTTP/1.1 200 OK
*
* {
* _id: '123',
* title: 'a title',
* text: 'a text',
* createdAt: '2017-05-03',
* author: {
* _id: '123312',
* username: 'Jon'
* },
* favorite: true
* }
*
* @apiErrorExample {json} Post not found
* HTTP/1.1 404 Not Found
* @apiErrorExample {json} Unauthorized
* HTTP/1.1 401 Unauthorized
*/
export async function getById(req, res, next) {
try {
const promise = await Promise.all([
User.findById(req.user._id),
Post.findById(req.params.id).populate('author'),
]);
const favorite = promise[0]._favorites.isPostIsFavorite(req.params.id);
return res.status(HTTPStatus.OK).json({
...promise[1].toJSON(),
favorite,
});
} catch (err) {
err.status = HTTPStatus.BAD_REQUEST;
return next(err);
}
}
/**
* @api {post} /posts Create a post
* @apiDescription Create a post
* @apiName createPost
* @apiGroup Post
*
* @apiParam (Body) {String} title Post title.
* @apiParam (Body) {String} text Post text.
*
* @apiHeader {Authorization} Authorization JWT Token
*
* @apiSuccess {Number} status Status of the Request.
* @apiSuccess {Object} post Post created.
* @apiSuccess {String} post._id Post _id.
* @apiSuccess {String} post.title Post title.
* @apiSuccess {String} post.text Post text.
* @apiSuccess {String} post.author Post author id.
* @apiSuccess {String} post.createdAt Post created date.
*
* @apiParam (Login) {String} pass Only logged in users can do this.
*
* @apiHeaderExample {json} Header-Example:
* {
* "AUTHORIZATION": "JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1OTBhMWI3ODAzMDI3N2NiNjQxM2JhZGUiLCJpYXQiOjE0OTM4MzQ2MTZ9.RSlMF6RRwAALZQRdfKrOZWnuHBk-mQNnRcCLJsc8zio"
* }
*
* @apiSuccessExample Success-Response:
*
* HTTP/1.1 200 OK
*
* {
* _id: '123',
* title: 'a title',
* text: 'a text',
* createdAt: '2017-05-03',
* author: '123312'
* }
*
* @apiErrorExample {json} Unauthorized
* HTTP/1.1 401 Unauthorized
*/
export async function create(req, res, next) {
const body = filteredBody(req.body, contants.WHITELIST.posts.create);
try {
return res
.status(HTTPStatus.CREATED)
.json(await Post.createPost(body, req.user._id));
} catch (err) {
err.status = HTTPStatus.BAD_REQUEST;
return next(err);
}
}
/**
* @api {delete} /posts/:id Delete a post
* @apiDescription Delete a post if the author it's the right one
* @apiName deletePost
* @apiGroup Post
*
* @apiHeader {Authorization} Authorization JWT Token
*
* @apiParam {String} id Post unique ID.
*
* @apiParam (Login) {String} pass Only logged in users can do this.
*
* @apiSuccess {Number} status Status of the Request.
*
* @apiHeaderExample {json} Header-Example:
* {
* "AUTHORIZATION": "JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1OTBhMWI3ODAzMDI3N2NiNjQxM2JhZGUiLCJpYXQiOjE0OTM4MzQ2MTZ9.RSlMF6RRwAALZQRdfKrOZWnuHBk-mQNnRcCLJsc8zio"
* }
*
* @apiSuccessExample Success-Response:
*
* HTTP/1.1 200 OK
*
* 200
*
* @apiErrorExample {json} Post not found
* HTTP/1.1 404 Not Found
* @apiErrorExample {json} Unauthorized
* HTTP/1.1 401 Unauthorized
*
*/
export async function deletePost(req, res, next) {
try {
const post = await Post.findById(req.params.id);
if (post.author.toString() !== req.user._id.toString()) {
return res.sendStatus(HTTPStatus.UNAUTHORIZED);
}
await post.remove();
return res.sendStatus(HTTPStatus.OK);
} catch (err) {
err.status = HTTPStatus.BAD_REQUEST;
return next(err);
}
}
/**
* @api {patch} /posts/:id Update a post
* @apiDescription Update a post if the author it's the right one
* @apiName updatePost
* @apiGroup Post
*
* @apiHeader {Authorization} Authorization JWT Token
*
* @apiParam {String} id Post unique ID.
*
* @apiParam (Body) {String} [title] Post title.
* @apiParam (Body) {String} [text] Post text.
*
* @apiSuccess {Number} status Status of the Request.
* @apiSuccess {Object} post Post updated.
* @apiSuccess {String} post._id Post _id.
* @apiSuccess {String} post.title Post title.
* @apiSuccess {String} post.text Post text.
* @apiSuccess {String} post.author Post author id.
* @apiSuccess {String} post.createdAt Post created date.
*
* @apiParam (Login) {String} pass Only logged in users can do this.
*
* @apiHeaderExample {json} Header-Example:
* {
* "AUTHORIZATION": "JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1OTBhMWI3ODAzMDI3N2NiNjQxM2JhZGUiLCJpYXQiOjE0OTM4MzQ2MTZ9.RSlMF6RRwAALZQRdfKrOZWnuHBk-mQNnRcCLJsc8zio"
* }
*
* @apiSuccessExample Success-Response:
*
* HTTP/1.1 200 OK
*
* {
* _id: '123',
* title: 'New title',
* text: 'New text',
* createdAt: '2017-05-03',
* author: '123312'
* }
*
* @apiErrorExample {json} Post not found
* HTTP/1.1 404 Not Found
* @apiErrorExample {json} Unauthorized
* HTTP/1.1 401 Unauthorized
*/
export async function updatePost(req, res, next) {
const body = filteredBody(req.body, contants.WHITELIST.posts.update);
try {
const post = await Post.findById(req.params.id);
if (post.author.toString() !== req.user._id.toString()) {
return res.sendStatus(HTTPStatus.UNAUTHORIZED);
}
Object.keys(body).forEach(key => {
post[key] = body[key];
});
return res.status(HTTPStatus.OK).json(await post.save());
} catch (err) {
err.status = HTTPStatus.BAD_REQUEST;
return next(err);
}
}
/**
* @api {post} /posts/:id/favorite Favorite a post
* @apiDescription Favorite a post or unfavorite if already.
* @apiName favoritePost
* @apiGroup Post
*
* @apiHeader {Authorization} Authorization JWT Token
*
* @apiParam {String} id Post unique ID.
*
* @apiSuccess {Number} status Status of the Request.
*
* @apiParam (Login) {String} pass Only logged in users can do this.
*
* @apiHeaderExample {json} Header-Example:
* {
* "AUTHORIZATION": "JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1OTBhMWI3ODAzMDI3N2NiNjQxM2JhZGUiLCJpYXQiOjE0OTM4MzQ2MTZ9.RSlMF6RRwAALZQRdfKrOZWnuHBk-mQNnRcCLJsc8zio"
* }
*
* @apiSuccessExample Success-Response:
*
* HTTP/1.1 200 OK
*
* @apiErrorExample {json} Post not found
* HTTP/1.1 404 Not Found
* @apiErrorExample {json} Unauthorized
* HTTP/1.1 401 Unauthorized
*/
export async function favoritePost(req, res, next) {
try {
const user = await User.findById(req.user._id);
await user._favorites.posts(req.params.id);
return res.sendStatus(HTTPStatus.OK);
} catch (err) {
err.status = HTTPStatus.BAD_REQUEST;
return next(err);
}
}