This repository has been archived by the owner on May 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ng.service.ts
executable file
·377 lines (356 loc) · 11.9 KB
/
ng.service.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
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
import { HttpServerService, Inject, Injectable, Request } from '@hapiness/core';
import { Compiler, CompilerFactory, NgModuleFactory, StaticProvider, Type } from '@angular/core';
import { INITIAL_CONFIG, platformDynamicServer, renderModuleFactory } from '@angular/platform-server';
import { ResourceLoader } from '@angular/compiler';
import { ModuleMap, provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';
import { Observable } from 'rxjs/Observable';
import { toArray, filter, flatMap, map, tap } from 'rxjs/operators';
import { mergeStatic } from 'rxjs/operators/merge';
import { of } from 'rxjs/observable/of';
import { fromPromise } from 'rxjs/observable/fromPromise';
import { _throw } from 'rxjs/observable/throw';
import * as fs from 'fs';
import { join } from 'path';
import { NG_UNIVERSAL_MODULE_CONFIG, REQUEST, RESPONSE, NgSetupOptions, StaticContent } from '../../interfaces';
import { HapinessHTTPHandlerResponse } from '@hapiness/core/extensions/http-server';
@Injectable()
export class NgEngineService {
/**
* This holds a cached version of each data used.
*/
private _dataCache: { [key: string]: Buffer };
/**
* Map of Module Factories
*/
private _factoryCacheMap: Map<Type<{}>, NgModuleFactory<{}>>;
/**
* Angular compiler factory
*/
private _compilerFactory: CompilerFactory;
/**
* Angular compiler instance
*/
private _compiler: Compiler;
/**
* Renders a {@link NgModuleFactory} to string.
*
* `document` is the full document HTML of the page to render, as a string.
* `url` is the URL for the current render request.
* `extraProviders` are the platform level providers for the current render request.
*
* store original function to stub it in tests
*/
private _renderModuleFactory: <T>(moduleFactory: NgModuleFactory<T>, options: {
document?: string;
url?: string;
extraProviders?: StaticProvider[];
}) => Promise<string>;
/**
* Helper function for getting the providers object for the MODULE_MAP
*
* @param {ModuleMap} moduleMap Map to use as a value for MODULE_MAP
*
* store original function to stub it in tests
*/
private _provideModuleMap: (moduleMap: ModuleMap) => StaticProvider;
/**
* Service constructor
*
* @param {NgSetupOptions} _config
* @param {HttpServerService} _httpServerService
*/
constructor(@Inject(NG_UNIVERSAL_MODULE_CONFIG) private _config: NgSetupOptions, private _httpServerService: HttpServerService) {
this._dataCache = {};
this._factoryCacheMap = new Map<Type<{}>, NgModuleFactory<{}>>();
this._compilerFactory = platformDynamicServer().injector.get(CompilerFactory);
this._compiler = this._compilerFactory.createCompiler([
{
providers: [
{ provide: ResourceLoader, useClass: FileLoader, deps: [] }
]
}
]);
this._renderModuleFactory = renderModuleFactory;
this._provideModuleMap = provideModuleMap;
}
/**
* Returns universal rendering of HTML
*
* @param {Request} request initial request
*
* @return {Observable<any | HapinessHTTPHandlerResponse>}
*/
universal(request: Request): Observable<any | HapinessHTTPHandlerResponse> {
return mergeStatic(
this._checkRequest(request),
this._checkConfig()
)
.pipe(
toArray(),
map(_ =>
({
request: <Request> _.shift(),
config: <NgSetupOptions> _.pop()
})
),
map(_ => Object.assign(_, { mime: this._httpServerService.instance().mime.path(_.request.raw.req.url).type })),
flatMap(_ => mergeStatic(
this._getStaticContent(_),
this._getFactoryContent(_)
)
)
);
}
/**
* Returns HapinessHTTPHandlerResponse from static content
*
* @param _
*
* @returns {Observable<HapinessHTTPHandlerResponse>}
*
* @private
*/
private _getStaticContent(_: any): Observable<HapinessHTTPHandlerResponse> {
return of(_)
.pipe(
filter(__ => !!__.mime),
flatMap(__ =>
of({
response: this._getDocument(this._buildFilePath(__.config.staticContent, __.mime, __.request.raw.req.url)),
headers: {
'content-type': __.mime
}
})
)
);
}
/**
* Returns content from NgFactoryModule
*
* @param _
*
* @returns {Observable<any>}
*
* @private
*/
private _getFactoryContent(_: any): Observable<any> {
return of(_)
.pipe(
filter(__ => !__.mime),
map(__ =>
({
moduleOrFactory: __.config.bootstrap,
extraProviders: this._extraProviders(
__.request,
__.config.providers,
__.config.lazyModuleMap,
this._buildFilePath(__.config.staticContent)
)
})
),
flatMap(__ =>
this._getFactory(__.moduleOrFactory)
.pipe(
flatMap(factory =>
fromPromise(this._renderModuleFactory(factory, { extraProviders: __.extraProviders }))
)
)
)
);
}
/**
* Function to check request parameter
*
* @param {Request} request
*
* @returns {Observable<Request>}
*
* @private
*/
private _checkRequest(request: Request): Observable<Request> {
return of(request)
.pipe(
flatMap(_ => (!!_ && !!_.raw && !!_.raw.req && _.raw.req.url !== undefined) ?
of(_) :
_throw(new Error('url is undefined'))
)
);
}
/**
* Function to check module config
*
* @returns {Observable<NgSetupOptions>}
*
* @private
*/
private _checkConfig(): Observable<NgSetupOptions> {
return of(this._config)
.pipe(
flatMap(_ => (!!_ && !!_.bootstrap) ?
of(_) :
_throw(new Error('You must pass in config a NgModule or NgModuleFactory to be bootstrapped'))
),
flatMap(_ => (!!_ && !!_.lazyModuleMap) ?
of(_) :
_throw(new Error('You must pass in config lazy module map'))
),
flatMap(_ => (!!_ && !!_.staticContent) ?
of(_) :
_throw(new Error('You must pass in config the static content object'))
),
flatMap(_ => (!!_ && !!_.staticContent.indexFile) ?
of(_) :
_throw(new Error('You must pass in config the static content object with index file'))
),
flatMap(_ => (!!_ && !!_.staticContent.rootPath) ?
of(_) :
_throw(new Error('You must pass in config the static content object with root path'))
),
flatMap(_ => of({
bootstrap: _.bootstrap,
lazyModuleMap: _.lazyModuleMap,
staticContent: _.staticContent,
providers: _.providers || []
})
)
);
}
/**
* Builds extra providers
*
* @param {Request} request
* @param {StaticProvider[]} providers
* @param {ModuleMap} lazyModuleMap
* @param {string} filePath
*
* @return {Provider[]}
*
* @private
*/
private _extraProviders(request: Request, providers: StaticProvider[], lazyModuleMap: ModuleMap, filePath: string): StaticProvider[] {
return providers!.concat(
providers!,
this._provideModuleMap(lazyModuleMap),
this._getRequestProviders(request),
[
{
provide: INITIAL_CONFIG,
useValue: {
document: this._getDocument(filePath).toString(),
url: request.raw.req.url
}
}
]
);
}
/**
* Get a factory from a bootstrapped module / module factory
*
* @param {Type<{}> | NgModuleFactory<{}>} moduleOrFactory
*
* @return {Observable<NgModuleFactory<{}>>}
*
* @private
*/
private _getFactory(moduleOrFactory: Type<{}> | NgModuleFactory<{}>): Observable<NgModuleFactory<{}>> {
return <Observable<NgModuleFactory<{}>>> of(
of(moduleOrFactory)
)
.pipe(
flatMap(obs =>
mergeStatic(
obs
.pipe(
filter(_ => _ instanceof NgModuleFactory)
),
obs
.pipe(
filter(_ => !(_ instanceof NgModuleFactory)),
map((_: Type<{}>) => this._factoryCacheMap.get(_)),
flatMap(_ => !!_ ? of(_) : this._compile(<Type<{}>> moduleOrFactory))
)
)
)
);
}
/**
* Compile the module and cache it
*
* @param {Type<{}>} module to compile and cache
*
* @return {Observable<NgModuleFactory<{}>>}
*
* @private
*/
private _compile(module: Type<{}>): Observable<NgModuleFactory<{}>> {
return <Observable<NgModuleFactory<{}>>> fromPromise(this._compiler.compileModuleAsync(module))
.pipe(
tap(_ => this._factoryCacheMap.set(module, _))
);
}
/**
* Get providers of the request and response
*
* @param {Request} request current request
*
* @return {StaticProvider[]}
*
* @private
*/
private _getRequestProviders(request: Request): StaticProvider[] {
return <StaticProvider[]> [
{
provide: REQUEST,
useValue: request
},
{
provide: RESPONSE,
useValue: request.raw.res
}
];
}
/**
* Returns document path
*
* @param {StaticContent} staticContent
* @param {string} mime
* @param {string} staticFileUrl
*
* @returns {string}
*
* @private
*/
private _buildFilePath(staticContent: StaticContent, mime?: string, staticFileUrl?: string): string {
return (!!mime && !!staticFileUrl) ?
join(staticContent.rootPath, staticFileUrl) :
join(staticContent.rootPath, staticContent.indexFile);
}
/**
* Returns document from cache or file system
*
* @param {string} filePath path to the file
*
* @return {Buffer}
*
* @private
*/
private _getDocument(filePath: string): Buffer {
return this._dataCache[filePath] = this._dataCache[filePath] || fs.readFileSync(filePath);
}
}
/**
* FileLoader implementation
*/
class FileLoader implements ResourceLoader {
/* istanbul ignore next */
get(url: string): Promise<string> {
return new Promise((resolve, reject) => {
fs.readFile(url, (err: NodeJS.ErrnoException, buffer: Buffer) => {
if (err) {
return reject(err);
}
resolve(buffer.toString());
});
});
}
}