This repository was archived by the owner on Dec 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathReactController.tsx
87 lines (71 loc) · 3.3 KB
/
ReactController.tsx
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
import {renderToString} from 'react-dom/server';
import {AsyncComponentProvider, createAsyncContext} from 'react-async-component';
import asyncBootstrapper from 'react-async-bootstrapper';
import * as serialize from 'serialize-javascript';
import * as path from 'path';
import * as fse from 'fs-extra';
import * as React from 'react';
import * as Hapi from 'hapi';
import RouterWrapper from '../../RouterWrapper';
import ProviderService from '../../services/ProviderService';
import rootSaga from '../../stores/rootSaga';
import ISagaStore from '../../interfaces/stores/ISagaStore';
import IStore from '../../interfaces/stores/IStore';
import IController from '../../interfaces/server/IController';
class ReactController implements IController {
private _html: string = null;
public mapRoutes(server: Hapi.Server): void {
server.route({
method: 'GET',
path: '/{route*}',
handler: async (request: Hapi.Request, reply: Hapi.ReplyNoContinue): Promise<void> => {
const store: ISagaStore<IStore> = ProviderService.createProviderStore({}, true);
const asyncContext: any = createAsyncContext();
const routeContext: any = {};
const app = (
<AsyncComponentProvider asyncContext={asyncContext}>
<RouterWrapper
store={store}
location={request.path}
context={routeContext}
isServerSide={true}
/>
</AsyncComponentProvider>
);
this._html = (this._html === null) ? await this._loadHtmlFile() : this._html;
await asyncBootstrapper(app);
store.runSaga(rootSaga).done.then(() => {
if (routeContext.url) {
return reply().redirect(routeContext.url);
}
const renderedHtml: string = renderToString(app);
const asyncComponentsState: IStore = asyncContext.getState();
const state: IStore = store.getState();
const initialState: IStore = {
...state,
renderReducer: {
isServerSide: true,
},
};
const html: string = this._html
.slice(0)
.replace('{title}', initialState.metaReducer.title)
.replace('{description}', initialState.metaReducer.description)
.replace('{content}', renderedHtml)
.replace('{state}', JSON.stringify(initialState))
.replace('{asyncComponentsState}', serialize(asyncComponentsState));
return reply(html);
}).catch((error: Error) => {
reply(error.toString());
});
renderToString(app);
store.endSaga();
},
});
}
private async _loadHtmlFile(): Promise<string> {
const htmlPath = path.resolve(__dirname, '../../public/index.html');
return fse.readFile(htmlPath, 'utf8');
}
}
export default ReactController;