-
Notifications
You must be signed in to change notification settings - Fork 42
/
server.js
104 lines (86 loc) · 2.43 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
100
101
102
103
104
/* jshint esversion: 6 */
const express = require('express')
const next = require('next')
const LRUCache = require('lru-cache')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dir: '.', dev })
const handle = app.getRequestHandler()
let cacheTime = 1000 * 60 * 60 // 1 hour
if (dev) {
cacheTime = 100
}
// This is where we cache our rendered HTML pages
const ssrCache = new LRUCache({
max: 100,
maxAge: cacheTime
})
app.prepare().then(() => {
const server = express()
// Use the `renderAndCache` utility defined below to serve pages
server.get('/', (req, res) => {
renderAndCache(req, res, '/')
})
server.get('/events', (req, res) => {
renderAndCache(req, res, '/events')
})
server.get('/events/:id', (req, res) => {
const queryParams = { id: req.params.id }
renderAndCache(req, res, '/single-event', queryParams)
})
server.get('/news', (req, res) => {
renderAndCache(req, res, '/news')
})
server.get('/news/:id', (req, res) => {
const queryParams = { id: req.params.id }
renderAndCache(req, res, '/single-news', queryParams)
})
server.get('/i/:id', (req, res) => {
const queryParams = { id: req.params.id }
renderAndCache(req, res, '/pdf-page', queryParams)
})
server.get('/search/*', (req, res) => {
renderAndCache(req, res, '/search')
})
server.get('*', (req, res) => {
return handle(req, res)
})
if (dev) {
server.listen(3000, err => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
} else {
server.listen(8080, err => {
if (err) throw err
console.log('> Ready on http://localhost:8080')
})
}
})
/*
* NB: make sure to modify this to take into account anything that should trigger
* an immediate page change (e.g a locale stored in req.session)
*/
function getCacheKey (req) {
return `${req.url}`
}
function renderAndCache (req, res, pagePath, queryParams) {
const key = getCacheKey(req)
// If we have a page in the cache, let's serve it
if (ssrCache.has(key)) {
console.log(`CACHE HIT: ${key}`)
res.send(ssrCache.get(key))
return
}
// If not let's render the page into HTML
app
.renderToHTML(req, res, pagePath, queryParams)
.then(html => {
// Let's cache this page
console.log(`CACHE MISS: ${key}`)
ssrCache.set(key, html)
res.send(html)
})
.catch(err => {
app.renderError(err, req, res, pagePath, queryParams)
})
}