Skip to content

Instantly share code, notes, and snippets.

@beeman
Created May 12, 2018 12:07
Show Gist options
  • Save beeman/e54e1fba366158bc22cbb903d49dfe2a to your computer and use it in GitHub Desktop.
Save beeman/e54e1fba366158bc22cbb903d49dfe2a to your computer and use it in GitHub Desktop.
import * as express from 'express';
import { join } from 'path';
import { ngExpressEngine } from '@nguniversal/express-engine';
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';
import * as compression from 'compression';
import * as cache from 'memory-cache';
const PORT = process.env.PORT || 8080;
const staticRoot = join(process.cwd(), 'dist', 'store');
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/store-server/main');
const app = express();
app.use(compression());
const memCache = new cache.Cache();
const cacheMiddleware = (duration) => {
return (req, res, next) => {
const key = '__express__' + req.originalUrl || req.url;
const cacheContent = memCache.get(key);
if (cacheContent) {
res.send(cacheContent);
return;
} else {
res.sendResponse = res.send;
res.send = (body) => {
memCache.put(key, body, duration * 1000);
res.sendResponse(body);
};
next();
}
};
};
app.engine('html', ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
}));
app.set('view engine', 'html');
app.set('views', staticRoot);
app.get('*.*', express.static(staticRoot));
app.get('*', cacheMiddleware(30), (req, res) => res.render('index', { req }));
app.listen(PORT, () => console.log(`Server listening on http://localhost:${PORT}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment