Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@fwertz
Last active November 11, 2015 06:06
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 fwertz/00ce1480d933d0799ce4 to your computer and use it in GitHub Desktop.
Save fwertz/00ce1480d933d0799ce4 to your computer and use it in GitHub Desktop.
Sample express.js routing
var express = require( 'express' ),
body = require( 'body-parser' ),
env = process.env;
App = express();
/**
* Load up the App.locals as a reference carrying singleton superstar
*/
App.locals = {
db: '...',
models: {
User: require( '...' )
}
}
/**
* Ext. Middleware or custom route modifers
*/
App.use( body.json() );
App.use( function ( req, res, next ) { /*..*/ next() } );
/**
* Depending on needs, sometimes these will separated out to another file for cleanliness
*/
App.use( '/', function ( req, res, next ) {
if ( !req.user ) {
res.redirect( '/login' );
}
});
App.use( '/login', function ( req, res, next ) {
res.render( 'login', { /* data */ } );
});
App.use( '/dist', express.static( __dirname + '/../public/dist' ) );
/**
* API / Data oriented routes
*
* Pass along a fresh router to keep middleware clean & separate, and let the App tag along too.
*/
var v1APIs = require( './routes/v1' )( express.Router(), App );
App.use( '/v1', v1APIs );
/**
* Expected / Unexpected errors
*/
App.use( function ( req, res, next ) {
res.status( 404 );
if ( req.accepts( 'json' ) ){
res.send( { /* ... */} );
} else if ( res.accepts( 'html' ) ) {
res.render( '404' );
} else {
res.send( 'Go back the way ya\' came, boy.' );
}
});
App.use( function ( err, req, res, next ) {
res.status( 500 );
if ( req.accepts( 'json' ) ){
if ( 'development' === env.NODE_ENV ) {
/* Maybe holl'a'tcha boi that err.stack so they can help ya' debug */
}
res.send( { /* ... */} );
} else if ( res.accepts( 'html' ) ) {
res.render( '500' );
} else {
res.send( 'Go back the way ya\' came, boy.' );
}
})
module.exports = function ( router, App ) {
var Users = App.locals.models.User,
ok = function ( data ) {
this.status( 200 ).send( data );
},
err = function ( err ) {
this.status( 500 ).send( err.message );
};
router.get( '/users/:id', function ( req, res, next ) {
Users
.where( 'id', req.params.id )
.findOne()
.then( ok.bind( res ), err.bind( res ) )
.catch( err.bind( res ) );
});
return router;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment