1 | import { CommonEngine } from '@nguniversal/common/engine';
|
2 | import { REQUEST, RESPONSE } from '@nguniversal/express-engine/tokens';
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | function ngExpressEngine(setupOptions) {
|
15 | const engine = new CommonEngine(setupOptions.bootstrap, setupOptions.providers);
|
16 | return function (filePath, options, callback) {
|
17 | try {
|
18 | const renderOptions = { ...options };
|
19 | if (!setupOptions.bootstrap && !renderOptions.bootstrap) {
|
20 | throw new Error('You must pass in a NgModule to be bootstrapped');
|
21 | }
|
22 | const { req } = renderOptions;
|
23 | const res = renderOptions.res ?? req.res;
|
24 | renderOptions.url =
|
25 | renderOptions.url ?? `${req.protocol}://${req.get('host') || ''}${req.baseUrl}${req.url}`;
|
26 | renderOptions.documentFilePath = renderOptions.documentFilePath ?? filePath;
|
27 | renderOptions.providers = [...(renderOptions.providers ?? []), getReqResProviders(req, res)];
|
28 |
|
29 | renderOptions.publicPath =
|
30 | renderOptions.publicPath ?? setupOptions.publicPath ?? options.settings?.views;
|
31 | renderOptions.inlineCriticalCss =
|
32 | renderOptions.inlineCriticalCss ?? setupOptions.inlineCriticalCss;
|
33 | engine
|
34 | .render(renderOptions)
|
35 | .then((html) => callback(null, html))
|
36 | .catch(callback);
|
37 | }
|
38 | catch (err) {
|
39 | callback(err);
|
40 | }
|
41 | };
|
42 | }
|
43 |
|
44 |
|
45 |
|
46 | function getReqResProviders(req, res) {
|
47 | const providers = [
|
48 | {
|
49 | provide: REQUEST,
|
50 | useValue: req,
|
51 | },
|
52 | ];
|
53 | if (res) {
|
54 | providers.push({
|
55 | provide: RESPONSE,
|
56 | useValue: res,
|
57 | });
|
58 | }
|
59 | return providers;
|
60 | }
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 | export { ngExpressEngine };
|
83 |
|