-
Notifications
You must be signed in to change notification settings - Fork 16
/
server.js
89 lines (72 loc) · 2.64 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
import { join } from 'path';
import cacheableResponse from 'cacheable-response';
import express from 'express';
import bodyParser from 'body-parser';
require('@babel/polyfill');
const next = require('next');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const IS_SSR_CACHE_ENABLED = !dev; // TODO move to config
// TODO: move to config
// Default 1 hour ttl
const ssrCache = (ttl) => {
return cacheableResponse({
ttl, // 1hour
get: async ({ req, res, pagePath, queryParams }) => {
console.log('Caching', req.url); // eslint-disable-line no-console
return ({
data: await app.renderToHTML(req, res, pagePath, queryParams),
});
},
send: ({ data, res }) => res.send(data),
});
};
Promise.all([
app.prepare(),
]).then(() => {
const server = express();
const sw = join(__dirname, '.next/service-worker.js');
const favicon = join(__dirname, '/static/images/favicon.ico');
const sitemap = join(__dirname, '/static/sitemap.xml');
const robots = join(__dirname, '/static/robots.txt');
const apple = join(__dirname, '/static/apple-app-site-association');
server.get('/sitemap.xml', (req, res) => {
app.serveStatic(req, res, sitemap);
});
server.get('/robots.txt', (req, res) => {
app.serveStatic(req, res, robots);
});
server.get('/favicon.ico', (req, res) => {
app.serveStatic(req, res, favicon);
});
server.get('/service-worker.js', (req, res) => {
app.serveStatic(req, res, sw);
});
server.get('/apple-app-site-association', (req, res) => {
// req.setHeader('Content-Type', 'application/json');
res.setHeader('Content-Type', 'application/json');
app.serveStatic(req, res, apple);
});
if (IS_SSR_CACHE_ENABLED) {
const homeCache = ssrCache(1000 * 60 * 60);
server.get('/', (req, res) => {
const queryParams = { id: req.params.id };
const pagePath = '/';
return homeCache({ req, res, pagePath, queryParams });
});
}
server.post('/value', bodyParser.json(), (req, res) => {
if (req?.body?.value) {
io.emit('data', req.body.value);
}
res.send('');
});
server.get('*', (req, res) => handle(req, res));
const serverInstance = server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`); // eslint-disable-line no-console
});
const io = require('socket.io')(serverInstance);
});