-
Notifications
You must be signed in to change notification settings - Fork 189
/
posts.js
112 lines (98 loc) · 3.07 KB
/
posts.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
require('../../lib/config');
const express = require('express');
const Post = require('../../data/post');
const { getPosts, getPostsCount } = require('../../utils/storage');
const { logger } = require('../../utils/logger');
const posts = express.Router();
posts.get('/', async (req, res) => {
const defaultNumberOfPosts = process.env.MAX_POSTS_PER_PAGE || 30;
const capNumOfPosts = 100;
const page = parseInt(req.query.page || 1, 10);
let ids;
let perPage;
let postsCount;
let from;
let to;
/**
* Set 'perPage' to a value within the limits or
* to default if per_page is not present
*/
if (req.query.per_page)
perPage = req.query.per_page > capNumOfPosts ? capNumOfPosts : req.query.per_page;
else perPage = defaultNumberOfPosts;
try {
postsCount = await getPostsCount();
/**
* Set the range of posts that will be requested
* {from, to}
*/
from = perPage * (page - 1);
// Make sure the upper limit is not higher than the total number of posts in the DB
to = perPage * page > postsCount ? postsCount : perPage * page;
ids = await getPosts(from, to);
} catch (err) {
logger.error({ err }, 'Unable to get posts from Redis');
res.status(503).json({
message: 'Unable to connect to database',
});
return;
}
/**
* Add prev, next, first and last in the response's header.
* It's been implemented to work circularly.
* Once reached the last set of posts, 'next' points at the first set.
* Same case with 'prev' and the first set of posts.
*/
const nextPage = to >= postsCount ? 1 : page + 1;
const prevPage = from === 0 ? Math.floor(postsCount / perPage) : page - 1;
res.set('X-Total-Count', postsCount);
res.links({
next: `/posts?per_page=${perPage}&page=${nextPage}`,
prev: `/posts?per_page=${perPage}&page=${prevPage}`,
first: `/posts?per_page=${perPage}&page=${1}`,
last: `/posts?per_page=${perPage}&page=${Math.floor(postsCount / perPage)}`,
});
res.json(
ids
// Return id and url for a specific post
.map((id) => ({
id,
url: `/posts/${id}`,
}))
);
});
posts.get('/:id', async (req, res) => {
const { id } = req.params;
try {
const post = await Post.byId(id);
// If the object we get back is empty, use 404
if (!post) {
res.status(404).json({
message: `Post not found for id ${id}`,
});
} else {
switch (req.accepts(['json', 'text', 'html'])) {
case 'json':
res.append('Content-type', 'application/json').json(post);
break;
case 'text':
res.append('Content-type', 'text/plain').send(post.text);
break;
case 'html':
res.append('Content-type', 'text/html').send(post.html);
break;
default:
res.status(406).json({
message: 'Invalid content type',
});
break;
}
}
} catch (err) {
logger.error({ err }, 'Unable to get posts from Redis');
res.status(503).json({
message: 'Unable to connect to database',
});
}
});
module.exports = posts;