UNPKG

universal-compiler-plugin-express

Version:
81 lines (74 loc) 2.5 kB
import _Promise from 'babel-runtime/core-js/promise'; import path from 'path'; import Express from 'express'; import favicon from 'serve-favicon'; import cookieParser from 'cookie-parser'; import compression from 'compression'; import config from 'application-runtime-config'; import { hooks, environments, register, execute } from 'universal-compiler'; var expressConfig = config.express; function buildServerPaths(assets) { return assets.map(function (absolutePath) { if (absolutePath.startsWith('http')) { return absolutePath; } var relativePath = path.relative(expressConfig.staticPath, absolutePath); if (relativePath.startsWith('/')) { return relativePath; } return '/' + relativePath; }); } register(hooks.SERVER_CREATE, function (_ref) { var assets = _ref.assets; var server = new Express(); var relativeAssets = { javascript: buildServerPaths(assets.javascript), styles: buildServerPaths(assets.styles) }; server.use(compression()); server.use(cookieParser()); if (expressConfig.faviconPath) { server.use(favicon(path.resolve(expressConfig.faviconPath))); } var maxAge = expressConfig.maxAge || 0; server.use(Express.static(path.resolve(expressConfig.staticPath), { maxage: maxAge })); server.use(function (req, res) { var params = { assets: relativeAssets, context: { location: req.originalUrl, headers: req.headers, cookies: req.cookies }, ssr: config.ssr }; execute(hooks.RENDER, _Promise.resolve(params)).then(function (_ref2) { var status = _ref2.status, body = _ref2.body, redirect = _ref2.redirect; if (redirect && config.ssr) { res.redirect(redirect); } else { res.status(status || 200).send(body); } }).catch(function (error) { res.status(500).send(error); console.error('Error rendering the request', error.stack); }); }); return { server: server }; }, { environments: environments.SERVER }); register(hooks.SERVER_START, function (_ref3) { var server = _ref3.server; return new _Promise(function (resolve, reject) { server.listen(expressConfig.port, function (err) { if (err) { console.error('Server failed to start: ', err.stack); return reject(err); } console.log('Server is listening on port ' + expressConfig.port); return resolve({ server: server }); }); }); }, { environments: environments.SERVER });