Skip to content

Instantly share code, notes, and snippets.

@DevJMD
Created May 21, 2016 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DevJMD/11ebffb6f7a6a131db012a6292756b41 to your computer and use it in GitHub Desktop.
Save DevJMD/11ebffb6f7a6a131db012a6292756b41 to your computer and use it in GitHub Desktop.
import Express from 'express';
import Nunjucks from 'nunjucks';
import BodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import * as Config from './config';
import * as LocalConfig from './locals';
export const App = Express();
export const Router = Express.Router();
export class Server {
static launch() {
/**
* Configure Nunjucks.
*
* 1. Autoescape is to safely escape HTML strings.
* 2. Declare App is using Express.
*/
Nunjucks.configure(Config.Server.viewPath, {
autoescape: true, /* [1] */
express: App /* [2] */
});
/**
* Set Express envrionment defaults.
*
* 1. Set the default view engine.
* 2. Set the Express environment.
*/
App.set('view engine', Config.Server.viewEngine); /* [1] */
App.set('env', Config.Server.envrionment); /* [2] */
/**
* Define local variables to be used in templates.
*/
for (const key of Object.keys(LocalConfig.Locals)) {
App.locals[key] = LocalConfig.Locals[key];
}
/**
* Set Express middleware.
*
* 1. Use Express .Router() middleware for routing.
* 2. Enable cookie parsing.
* 3. Enable body parsing, parsing the request input from the client-side.
* 4. Define the static asset URL.
* 5. Use session middleware to remember session states.
*/
App.use(Router); /* [1] */
App.use(cookieParser()); /* [2] */
App.use(BodyParser.urlencoded({ extended: true })); /* [3] */
App.use(`/${Config.Server.assetURL}`, Express.static(Config.Server.assetPath)); /* [4] */
App.use(session({ /* [5] */
secret: '92463294092482374234723',
name: `${Config.Server.namespace}-session`,
resave: true,
saveUninitialized: true
}));
/**
* Check if the configured environment is set to production.
*/
App.locals.isProduction = (App.get('env') === 'production');
/**
* Listen on the configured port.
*/
let server = App.listen(Config.Server.port, !App.locals.isProduction ? Config.Server.host : '0.0.0.0', () => {
console.log(`Server running @ http://${server.address().address}:${server.address().port}`);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment