-
Notifications
You must be signed in to change notification settings - Fork 482
/
main.ts
166 lines (146 loc) · 4.25 KB
/
main.ts
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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as fs from 'fs';
import { Request, Response } from 'express';
import { NgModuleFactory, Type, CompilerFactory, Compiler, StaticProvider } from '@angular/core';
import { ResourceLoader } from '@angular/compiler';
import {
INITIAL_CONFIG,
renderModuleFactory,
platformDynamicServer
} from '@angular/platform-server';
import { FileLoader } from './file-loader';
import { REQUEST, RESPONSE } from '@nguniversal/express-engine/tokens';
/**
* These are the allowed options for the engine
*/
export interface NgSetupOptions {
bootstrap: Type<{}> | NgModuleFactory<{}>;
providers?: StaticProvider[];
}
/**
* These are the allowed options for the render
*/
export interface RenderOptions extends NgSetupOptions {
req: Request;
res?: Response;
url?: string;
document?: string;
}
/**
* This holds a cached version of each index used.
*/
const templateCache: { [key: string]: string } = {};
/**
* Map of Module Factories
*/
const factoryCacheMap = new Map<Type<{}>, NgModuleFactory<{}>>();
/**
* This is an express engine for handling Angular Applications
*/
export function ngExpressEngine(setupOptions: NgSetupOptions) {
const compilerFactory: CompilerFactory = platformDynamicServer().injector.get(CompilerFactory);
const compiler: Compiler = compilerFactory.createCompiler([
{
providers: [
{ provide: ResourceLoader, useClass: FileLoader, deps: [] }
]
}
]);
return function (filePath: string,
options: RenderOptions,
callback: (err?: Error | null, html?: string) => void) {
options.providers = options.providers || [];
try {
const moduleOrFactory = options.bootstrap || setupOptions.bootstrap;
if (!moduleOrFactory) {
throw new Error('You must pass in a NgModule or NgModuleFactory to be bootstrapped');
}
setupOptions.providers = setupOptions.providers || [];
const req = options.req;
const extraProviders = setupOptions.providers.concat(
options.providers,
getReqResProviders(options.req, options.res),
[
{
provide: INITIAL_CONFIG,
useValue: {
document: options.document || getDocument(filePath),
url: options.url || req.protocol + '://' + (req.get('host') || '') + req.originalUrl
}
}
]);
getFactory(moduleOrFactory, compiler)
.then(factory => {
return renderModuleFactory(factory, {
extraProviders
});
})
.then((html: string) => {
callback(null, html);
}, (err) => {
callback(err);
});
} catch (err) {
callback(err);
}
};
}
/**
* Get a factory from a bootstrapped module/ module factory
*/
function getFactory(
moduleOrFactory: Type<{}> | NgModuleFactory<{}>, compiler: Compiler
): Promise<NgModuleFactory<{}>> {
return new Promise<NgModuleFactory<{}>>((resolve, reject) => {
// If module has been compiled AoT
if (moduleOrFactory instanceof NgModuleFactory) {
resolve(moduleOrFactory);
return;
} else {
let moduleFactory = factoryCacheMap.get(moduleOrFactory);
// If module factory is cached
if (moduleFactory) {
resolve(moduleFactory);
return;
}
// Compile the module and cache it
compiler.compileModuleAsync(moduleOrFactory)
.then((factory) => {
factoryCacheMap.set(moduleOrFactory, factory);
resolve(factory);
}, (err => {
reject(err);
}));
}
});
}
/**
* Get providers of the request and response
*/
function getReqResProviders(req: Request, res?: Response): StaticProvider[] {
const providers: StaticProvider[] = [
{
provide: REQUEST,
useValue: req
}
];
if (res) {
providers.push({
provide: RESPONSE,
useValue: res
});
}
return providers;
}
/**
* Get the document at the file path
*/
function getDocument(filePath: string): string {
return templateCache[filePath] = templateCache[filePath] || fs.readFileSync(filePath).toString();
}