-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
91 lines (70 loc) · 2.01 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
require('dotenv').config()
const dev = process.env.NODE_ENV !== 'production'
const moduleAlias = require('module-alias')
if (!dev) {
moduleAlias.addAlias('react', 'preact-compat')
moduleAlias.addAlias('react-dom', 'preact-compat')
if (process.env.NOW_LOGS_KEY) {
require('now-logs')(process.env.NOW_LOGS_KEY)
}
}
const { parse } = require('url')
const { Server } = require('http')
const express = require('express')
const socketIO = require('socket.io')
const LRUCache = require('lru-cache')
const next = require('next')
const tweets = require('./lib/tweetStream')
const nextApp = next({ dir: '.', dev })
const handle = nextApp.getRequestHandler()
const ssrCache = new LRUCache({
max: 100,
maxAge: 1000 * 60 * 60 * 24 // 24h
})
const cachedRender = (req, res, pagePath, queryParams) => {
const key = `${req.url}`
if (!dev && ssrCache.has(key)) {
res.append('X-Cache', 'HIT')
res.send(ssrCache.get(key))
return
}
nextApp.renderToHTML(req, res, pagePath, queryParams)
.then(html => {
ssrCache.set(key, html)
res.append('X-Cache', 'MISS')
res.send(html)
})
.catch(err => {
nextApp.renderError(err, req, res, pagePath, queryParams)
})
}
const PORT = process.env.PORT || 3000
nextApp.prepare()
.then(() => {
const app = express()
const server = Server(app);
app.disable('x-powered-by')
app.get('/', (req, res) => {
cachedRender(req, res, '/')
})
app.get('*', (req, res) => {
const parsedUrl = parse(req.url, true)
handle(req, res, parsedUrl)
})
const io = socketIO(server)
io.on('connection', socket => {
console.log('User connected. Socket id %s', socket.id);
socket.on('disconnect', () => {
console.log('User disconnected. %s. Socket id %s', socket.id);
})
});
server.listen(PORT, err => {
if (err) {
throw err
}
tweets(data => {
io.sockets.emit('tweet', data)
})
console.log(`> Ready on http://localhost:${PORT}`)
})
})