Created
January 10, 2015 21:54
-
-
Save rrichardson/27784b3771ff8044c1e2 to your computer and use it in GitHub Desktop.
ExpressJS boilerplate / starter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require("express"); | |
var expressSession = require("express-session"); | |
var bodyParser = require("body-parser"); | |
var http = require("http"); | |
var path = require("path"); | |
var passport = require("passport"); | |
var router = require("./app/router"); | |
var UoW = require("./app/db/uow"); | |
var SocketIOHandler = require("./app/socketio_handler"); | |
require("./app/configure_passport")(); | |
function Application() { | |
this.apiRoutePrefix = "/api"; | |
this.configureMiddleware = function() { | |
this.app.use(function(req, res, next) { | |
req.homeDir = __dirname; | |
next(); | |
}) | |
.use(bodyParser.json()) | |
.use(bodyParser.urlencoded({extended: true})) | |
.use("/static", express.static(path.join(__dirname, "static"))) | |
.use(expressSession({ | |
secret: 'super secret key', | |
saveUninitialized: true, | |
resave: true | |
})) | |
.use(passport.initialize()) | |
.use(passport.session()) | |
.use(this.apiRoutePrefix, function(req, res, next) { | |
// define stuff available to all routes | |
req.uow = new UoW(); | |
req.requireLogin = function() { | |
if (!req.user) { | |
res.status(401).send(); | |
return false; | |
} | |
return true; | |
}; | |
res.header("Content-Type", "application/json"); | |
next(); | |
}); | |
return this; | |
}; | |
this.configureSettings = function() { | |
this.app | |
.set("view engine", "jade") | |
.set("views", path.join(__dirname, "views")) | |
.set("port", process.env.PORT || 8081); | |
return this; | |
}; | |
this.configureRoutes = function() { | |
router.register(this.apiRoutePrefix, this.app); | |
return this; | |
}; | |
this.startServer = function() { | |
var self = this; | |
this.server = http.createServer(this.app); | |
this.server.listen(this.app.get("port"), function() { | |
console.log('Express server listening on port ' + self.app.get('port')); | |
}); | |
return this; | |
}; | |
this.startSocketIO = function() { | |
(new SocketIOHandler(this.server)).connect(); | |
return this; | |
}; | |
this.run = function() { | |
this.app = express(); | |
this.configureMiddleware() | |
.configureSettings() | |
.configureRoutes() | |
.startServer() | |
.startSocketIO(); | |
} | |
} | |
(new Application()).run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment