@ngx-universal/express-engine
Version:
Express engine for Angular Universal
63 lines (62 loc) • 2.33 kB
JavaScript
import { ApplicationRef } from '@angular/core';
import { platformServer, platformDynamicServer, PlatformState, INITIAL_CONFIG } from '@angular/platform-server';
import * as fs from 'fs';
var templateCache = {};
function getRequestResponseProviders(req, res) {
var providers = [
{
provide: 'REQUEST',
useValue: req
}
];
if (res)
providers.push({
provide: 'RESPONSE',
useValue: res
});
return providers;
}
function getDocument(filePath) {
return templateCache[filePath] = templateCache[filePath] || fs.readFileSync(filePath).toString();
}
function handleModuleRef(moduleRef, callback) {
var state = moduleRef.injector.get(PlatformState);
var appRef = moduleRef.injector.get(ApplicationRef);
appRef.isStable
.filter(function (isStable) { return isStable; })
.first()
.subscribe(function () {
var bootstrap = moduleRef.instance['ngOnBootstrap'];
bootstrap();
callback(null, state.renderToString());
moduleRef.destroy();
});
}
export function ngExpressEngine(setupOptions) {
setupOptions.providers = setupOptions.providers || [];
return function (filePath, options, callback) {
try {
var moduleFactory = setupOptions.bootstrap;
if (!moduleFactory)
throw new Error('You must pass in a NgModule or NgModuleFactory to be bootstrapped');
var extraProviders = setupOptions.providers.concat(getRequestResponseProviders(options.req, options.res), [
{
provide: INITIAL_CONFIG,
useValue: {
document: getDocument(filePath),
url: options.req.originalUrl
}
}
]);
var moduleRefPromise = setupOptions.aot ?
platformServer(extraProviders).bootstrapModuleFactory(moduleFactory) :
platformDynamicServer(extraProviders).bootstrapModule(moduleFactory);
moduleRefPromise.then(function (moduleRef) {
handleModuleRef(moduleRef, callback);
});
}
catch (e) {
callback(e);
}
};
}