-
Notifications
You must be signed in to change notification settings - Fork 16
/
server.pd.js
102 lines (85 loc) · 2.6 KB
/
server.pd.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
/**
* Author: ひまわり(dtysky<[email protected]>)
* Github: https://github.com/dtysky
* Created: 16/12/29
*/
import React from 'react';
import {renderToString} from 'react-dom/server';
import {StaticRouter} from 'react-router-dom';
import multer from 'multer';
import express from 'express';
import path from 'path';
import fs from 'fs';
import zlib from 'zlib';
import genMeta from './demo/src/genMeta';
import App from './demo/src/App';
/* -- wtf ? -- */
if (typeof window === 'undefined') {
global.window = {};
}
if (typeof document === 'undefined') {
global.document = {};
}
/* -- wtf ! -- */
const port = 8888;
const storage = multer.memoryStorage();
const upload = multer({storage});
const app = new express();
const template = fs.readFileSync(path.resolve(__dirname, './demo/dist/index.html'), 'utf8');
app.post('/upload', upload.any(), (req, res) => {
if (!req.files) {
return res.status(400).send('No files were uploaded.');
}
return res.status(200).send('蛤蛤');
});
app.use((req, res, next) => {
if (['.js', '.css'].indexOf(path.extname(req.url)) >= 0) {
res.setHeader('Content-Encoding', 'gzip');
}
return next();
});
app.use('/demo/static', express.static(path.resolve(__dirname, './demo/static')));
app.use('/demo', express.static(path.resolve(__dirname, './demo/dist')));
app.get('/sitemap-http', (req, res) => res.sendFile(path.resolve(__dirname, './demo/sitemap-http.xml')));
app.get('/sitemap-https', (req, res) => res.sendFile(path.resolve(__dirname, './demo/sitemap-https.xml')));
const cache = {};
function ssr(req, res) {
const {url} = req;
if (cache[url]) {
// logInfo('Get from cache: ', frontUrl, ', backend: ', backUrl);
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Encoding', 'gzip');
return res.send(cache[url]);
}
const context = {};
const markup = renderToString(
<StaticRouter location={url} context={context}>
<App />
</StaticRouter>
);
if (context.url) {
return res.redirect(302, context.url);
}
const {title, description} = genMeta(url);
cache[url] = zlib.gzipSync(
template
.replace('{{MARKUP}}', markup)
.replace('{{TITLE}}', title)
.replace('{{DESCRIPTION}}', description),
{level: 9}
);
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Encoding', 'gzip');
res.send(cache[url]);
}
app.use(ssr);
app.get('*', (req, res) =>
res.send(template)
);
app.listen(port, error => {
if (error) {
console.error(error);
} else {
console.info('==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port);
}
});