This repository has been archived by the owner on Sep 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
reduxApp.js
319 lines (289 loc) · 8.25 KB
/
reduxApp.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import fs from "fs";
import path from "path";
import { inspect } from "util";
import React from "react";
import { ServerStyleSheet } from "styled-components";
import {
renderToNodeStream,
renderToStaticNodeStream,
renderToStaticMarkup
} from "react-dom/server";
import { createMemoryHistory, match } from "react-router";
import { syncHistoryWithStore } from "react-router-redux";
import { loadOnServer } from "redux-async-loader";
import Fetchr from "fetchr";
import { flushChunkNames } from "react-universal-component/server";
import flushChunks from "webpack-flush-chunks";
import { mapValues, noop, transform } from "lodash/fp";
import debugFactory from "debug";
import createStore from "shared/redux/createStore";
import getRoutes from "shared/routes";
import Html from "server/components/Html";
import App from "server/components/App";
const debug = debugFactory("app:server:middleware:reduxApp");
const logger = __DEVELOPMENT__
? store => next => action => {
debug(`Invoking action: ${inspect(action).replace(/\s*\n\s*/g, " ")}`);
return next(action);
}
: null;
export default function createReduxApp(config) {
const maxAge = Math.floor(config.offload.cache.maxAge / 1000);
const cssChunks = __DEVELOPMENT__ ? null : loadCssChunks(config);
/*
* 全リクエストで共有される初期データのためのStoreです。
*/
const initialStore = createStore(
{},
{
cookie: [{ cookies: {} }, {}],
fetchr: new Fetchr({ ...config.fetchr, req: {} }),
history: createMemoryHistory("/"),
logger
}
);
return reduxApp;
/*
* サーバサイドレンダリングのためのExpressミドルウェアです。
*/
function reduxApp(req, res, next) {
const memoryHistory = createMemoryHistory(req.url);
const timing = __DEVELOPMENT__ ? res : { startTime: noop, endTime: noop };
/*
* リクエスト毎のStoreです。
* 共有の初期ストアのステートを初期ステートとして使用します。
*/
const store = createStore(initialStore.getState(), {
cookie: [req, res],
fetchr: new Fetchr({ ...config.fetchr, req }),
history: memoryHistory,
logger
});
const history = syncHistoryWithStore(memoryHistory, store);
const clientConfig = getClientConfig(config, req);
if (__DISABLE_SSR__) {
return void renderCSR({ res, store, config, clientConfig, timing });
}
/*
* 高負荷時にSSRをスキップするモードです。
* オフロードモードをサポートしない場合は ./offloadDetector.js と一緒に削除してください。
*/
if (__ENABLE_OFFLOAD__) {
debug("offload mode, disable server-side rendering");
res.set("cache-control", `max-age=${maxAge}`);
return void renderCSR({ res, store, config, clientConfig, timing });
}
/*
* React-Routerのルーティング定義とマッチングを行います。
*/
matchRoutes({ history, routes: getRoutes(store) })
.then(({ redirectLocation, renderProps }) => {
if (redirectLocation) {
return res.redirect(
302,
redirectLocation.pathname + redirectLocation.search
);
}
if (!renderProps) {
return next();
}
/*
* 初期表示に必要なデータをフェッチします。
*/
timing.startTime("prefetch", "Prefetch onLoad");
return Promise.all([
loadOnServer(renderProps, store),
// store.dispatch(checkLogin()).catch(() => null)
]).then(() => {
timing.endTime("prefetch");
/*
* サーバサイドレンダリングを行います。
*/
renderSSR({
res,
store,
renderProps,
config,
clientConfig,
cssChunks,
timing
});
});
})
.catch(err => {
debug(err);
debug(store.getState().routing);
return next(err);
});
}
}
function getClientConfig(config, req) {
const { fetchr, ...clientConfig } = config.clientConfig;
const csrfToken = req.csrfToken();
return {
...clientConfig,
fetchr: {
...fetchr,
context: {
...fetchr.context,
_csrf: csrfToken
}
},
csrfToken
};
}
function matchRoutes(options) {
return new Promise((resolve, reject) => {
match(options, (error, redirectLocation, renderProps) => {
if (error) {
reject(error);
} else {
resolve({ redirectLocation, renderProps });
}
});
});
}
function renderCSR({ res, store, config, clientConfig, timing }) {
const assets = flushChunks(config.clientStats);
sendCSRResponse({ res, store, status: 200, clientConfig, assets, timing });
}
function renderSSR({
res,
store,
renderProps,
config,
clientConfig,
cssChunks,
timing
}) {
/*
* メインコンテンツをレンダリングします。
*/
const sheet = new ServerStyleSheet(); // <-- creating out stylesheet
const jsx = sheet.collectStyles(<App store={store} {...renderProps} />)
const stream = sheet.interleaveWithNodeStream(renderToNodeStream(jsx))
const styles = sheet.getStyleTags();
const assets = getAssets({ clientStats: config.clientStats, cssChunks });
const { routes } = renderProps;
const status = routes[routes.length - 1].status || 200;
sendSSRResponse({
res,
status,
store,
stream,
clientConfig,
assets,
timing,
styles
});
}
function sendCSRResponse({
res,
status,
store,
clientConfig,
content,
assets,
timing
}) {
timing.startTime("html", "Rendering HTML");
const props = {
content,
assets,
initialState: JSON.stringify(store.getState()),
clientConfig: JSON.stringify(clientConfig)
};
const html = renderToStaticMarkup(<Html {...props} />);
timing.endTime("html");
res.status(status).send(`<!doctype html>\n${html}`);
}
function sendSSRResponse({
res,
status,
store,
clientConfig,
assets,
stream,
timing,
styles
}) {
/*
* HTML全体をレンダリングします。
*/
timing.startTime("html", "Rendering HTML");
timing.startTime("ssr", "Server Side Rendering");
let content = "";
stream.on("data", chunk => {
content += chunk;
});
stream.on("end", () => {
timing.endTime("ssr");
const props = {
content,
assets,
styles,
initialState: JSON.stringify(store.getState()),
clientConfig: JSON.stringify(clientConfig)
};
const htmlStream = renderToStaticNodeStream(<Html {...props} />);
htmlStream.on("end", () => {
timing.endTime("html");
});
htmlStream.pipe(res);
});
}
/*
* CSSファイルをロードします。
*/
function loadCssChunks({ clientStats, assets }) {
debug(Object.keys(clientStats));
const { path: outputPath } = assets.find(asset => asset.buildOutput);
const { assetsByChunkName: chunks, publicPath } = clientStats;
return transform(
(result, chunkName) => {
const chunkArray = ensureArray(chunks[chunkName]);
const cssChunk = chunkArray.find(chunk => chunk.endsWith(".css"));
if (cssChunk) {
result[cssChunk] = {
href: `${publicPath}${cssChunk}`,
content: fs.readFileSync(path.join(outputPath, cssChunk), "utf-8")
};
}
return result;
},
{},
Object.keys(chunks)
);
}
function ensureArray(v) {
if (v == null) {
return [];
}
if (Array.isArray(v)) {
return v;
}
return [v];
}
/*
* コードスプリットされたチャンクに関する情報を収集します。
* SSRで実際に使用されたチャンクのみをレンダリングできるようにします。
*/
function getAssets({ clientStats, cssChunks }) {
const chunkNames = flushChunkNames();
const assets = flushChunks(clientStats, { chunkNames });
const { publicPath } = assets;
const stylesheets = assets.stylesheets.map(
stylesheet => `${publicPath}/${stylesheet}`
);
assets.cssHashRaw = mapValues(
value => (stylesheets.includes(value) ? "loaded" : value)
)(assets.cssHashRaw);
if (!__DISABLE_INLINE_CSS__) {
assets.inlineStylesheets = assets.stylesheets.map(chunkName => ({
name: chunkName,
content: cssChunks[chunkName].content
}));
assets.stylesheets = null;
}
return assets;
}