This repository has been archived by the owner on Jun 2, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.js
99 lines (81 loc) · 2.4 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
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
const express = require('express');
const next = require('next');
const LRUCache = require('lru-cache');
const fetch = require('isomorphic-fetch');
const { format } = require('url');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handler = app.getRequestHandler();
const apiCache = new LRUCache({
max: 2000,
maxAge: 1000 * 60 * 60, // 1 hour
});
const ssrCache = new LRUCache({
max: 100,
maxAge: 1000 * 60 * 60, // 1 hour
});
/**
* Check if the page is already in cache and render it if not
* @method renderAndCache
* @param {Object} req The HTTP request
* @param {Object} res The HTTP response
* @param {string} pagePath The page to render
* @param {Object} queryParams The query params to use
*/
function renderAndCache(req, res, pagePath, queryParams) {
const key = req.url;
if (ssrCache.has(key)) {
process.stdout.write(`SSR CACHE HIT: ${key}\n`);
res.send(ssrCache.get(key));
return;
}
app
.renderToHTML(req, res, pagePath, queryParams)
.then((html) => {
process.stdout.write(`SSR CACHE MISS: ${key}\n`);
ssrCache.set(key, html);
res.send(html);
})
.catch((error) => {
app.renderError(error, req, res, pagePath, queryParams);
});
}
/**
* Check if the API response is in cache and fetch it if not
* @method fetchAndCache
* @param {Object} req The HTTP request
* @param {Object} res The HTTP response
* @param {Object} queryParams The query params to use
*/
function fetchAndCache(req, res, query) {
const key = format({
protocol: 'https',
pathname: '/v1/search',
hostname: 'api.spotify.com',
query,
});
if (apiCache.has(key)) {
process.stdout.write(`API CACHE HIT: ${key}\n`);
res.json(JSON.parse(apiCache.get(key)));
return;
}
fetch(key)
.then(response => response.json())
.then((data) => {
process.stdout.write(`API CACHE MISS: ${key}\n`);
apiCache.set(key, JSON.stringify(data));
res.json(data);
})
.catch(() => {
res.status(500).send('Error');
});
}
app
.prepare()
.then(() => {
const server = express();
server.get('/results', (req, res) => renderAndCache(req, res, '/results', req.query));
server.get('/api', (req, res) => fetchAndCache(req, res, req.query));
server.get('*', (req, res) => handler(req, res));
server.listen(process.env.PORT || 3000);
});