initial commit

This commit is contained in:
Art Lowel
2016-11-30 15:13:29 +01:00
commit a573556963
50 changed files with 2161 additions and 0 deletions

147
src/server.aot.ts Normal file
View File

@@ -0,0 +1,147 @@
// the polyfills must be one of the first things imported in node.js.
// The only modules to be imported higher - node modules with es6-promise 3.x or other Promise polyfill dependency
// (rule of thumb: do it if you have zone.js exception that it has been overwritten)
// if you are including modules that modify Promise, such as NewRelic,, you must include them before polyfills
import 'angular2-universal-polyfills';
import 'ts-helpers';
import './__workaround.node'; // temporary until 2.1.1 things are patched in Core
import * as fs from 'fs';
import * as path from 'path';
import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as cookieParser from 'cookie-parser';
import * as morgan from 'morgan';
import * as mcache from 'memory-cache';
const { gzipSync } = require('zlib');
const accepts = require('accepts');
const { compressSync } = require('iltorb');
const interceptor = require('express-interceptor');
// Angular 2
import { enableProdMode } from '@angular/core';
// Angular 2 Universal
import { createEngine } from 'angular2-express-engine';
// App
import { MainModuleNgFactory } from './node.module.ngfactory';
// Routes
import { routes } from './server.routes';
// enable prod for faster renders
enableProdMode();
const app = express();
const ROOT = path.join(path.resolve(__dirname, '..'));
// Express View
app.engine('.html', createEngine({
precompile: false, // this needs to be false when using ngFactory
ngModule: MainModuleNgFactory,
providers: [
// use only if you have shared state between users
// { provide: 'LRU', useFactory: () => new LRU(10) }
// stateless providers only since it's shared
]
}));
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname);
app.set('view engine', 'html');
app.set('json spaces', 2);
app.use(cookieParser('Angular 2 Universal'));
app.use(bodyParser.json());
app.use(interceptor((req, res)=>({
// don't compress responses with this request header
isInterceptable: () => (!req.headers['x-no-compression']),
intercept: ( body, send ) => {
const encodings = new Set(accepts(req).encodings());
const bodyBuffer = new Buffer(body);
// url specific key for response cache
const key = '__response__' + req.originalUrl || req.url;
let output = bodyBuffer;
// check if cache exists
if (mcache.get(key) === null) {
// check for encoding support
if (encodings.has('br')) {
// brotli
res.setHeader('Content-Encoding', 'br');
output = compressSync(bodyBuffer);
mcache.put(key, {output, encoding: 'br'});
} else if (encodings.has('gzip')) {
// gzip
res.setHeader('Content-Encoding', 'gzip');
output = gzipSync(bodyBuffer);
mcache.put(key, {output, encoding: 'gzip'});
}
} else {
const { output, encoding } = mcache.get(key);
res.setHeader('Content-Encoding', encoding);
send(output);
}
send(output);
}
})));
const accessLogStream = fs.createWriteStream(ROOT + '/morgan.log', {flags: 'a'})
app.use(morgan('common', {
skip: (req, res) => res.statusCode < 400,
stream: accessLogStream
}));
function cacheControl(req, res, next) {
// instruct browser to revalidate in 60 seconds
res.header('Cache-Control', 'max-age=60');
next();
}
// Serve static files
app.use('/assets', cacheControl, express.static(path.join(__dirname, 'assets'), {maxAge: 30}));
app.use(cacheControl, express.static(path.join(ROOT, 'dist/client'), {index: false}));
//
/////////////////////////
// ** Example API
// Notice API should be in a separate process
import { serverApi, createTodoApi } from './backend/api';
// Our API for demos only
app.get('/data.json', serverApi);
app.use('/api', createTodoApi());
function ngApp(req, res) {
res.render('index', {
req,
res,
// time: true, // use this to determine what part of your app is slow only in development
preboot: false,
baseUrl: '/',
requestUrl: req.originalUrl,
originUrl: `http://localhost:${ app.get('port') }`
});
}
/**
* use universal for specific routes
*/
app.get('/', ngApp);
routes.forEach(route => {
app.get(`/${route}`, ngApp);
app.get(`/${route}/*`, ngApp);
});
app.get('*', function(req, res) {
res.setHeader('Content-Type', 'application/json');
var pojo = { status: 404, message: 'No Content' };
var json = JSON.stringify(pojo, null, 2);
res.status(404).send(json);
});
// Server
let server = app.listen(app.get('port'), () => {
console.log(`Listening on: http://localhost:${server.address().port}`);
});