Last active
August 29, 2015 14:05
-
-
Save sixlettervariables/fe36adb9cf3e65f17b5f to your computer and use it in GitHub Desktop.
express-enrouten Router Dumper
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
/** router-dump: Dump the current stack for an expressjs router built with express-enrouten. | |
* @author Christopher A. Watford <[email protected]> | |
*/ | |
'use strict'; | |
/* EXAMPLE OUTPUT | |
[router] GET /login/ (./controllers/login/index.js) | |
[router] POST /login/ (./controllers/login/index.js) | |
[router] GET /login/reset/ (./controllers/login/index.js) | |
// ./controllers/login/index.js | |
module.exports = function (router) { | |
router.get('/', function (req, res) { | |
// ... | |
}); | |
router.post('/', function (req, res) { | |
// ... | |
}); | |
router.get('/reset', function (req, res) { | |
// ... | |
}); | |
require('../../lib/router-dump')(__filename, router); | |
}; | |
*/ | |
var path = require('path'); | |
var caller = require('caller'); | |
var parts = __dirname.split(path.sep); parts.pop(); | |
var appPath = path.sep + path.join.apply(null, parts); | |
/** | |
* Use like: require('./router-dump')(__filename, router); | |
*/ | |
module.exports = function (filename, router) { | |
var basepath = nameify(filename); | |
var who = caller().replace(appPath, ''); | |
router.stack.forEach(function (handler) { | |
if (!handler.route) return; | |
var methods = "*"; | |
if (handler.route.methods) { | |
methods = lpad(Object.keys(handler.route.methods).map(function (mm) { return mm.toUpperCase(); }).join(','),8); | |
} | |
console.log('[router] %s %s (.%s)', methods, lpad(basepath+handler.route.path, 40), who); | |
}); | |
}; | |
/** Left pad a string to a given length. | |
* @param str String to left pad with spaces. | |
* @param sz Size of the resulting string. | |
* @returns {String} [str] padded to [sz] places. | |
*/ | |
var pad = ' '; | |
function lpad(str, sz) { | |
return str+(str.length < sz ? pad.substr(0, sz - str.length) : ''); | |
}; | |
/** Convert an express-enrouten directory/filename into a route name. | |
* @param filename Filename of the controller. | |
* @returns {String} The actual route seen by express-enrouten. | |
*/ | |
function nameify(filename) { | |
var basepath = path.basename(filename, '.js'); | |
var baseparts = path.dirname(filename).split(path.sep); | |
if (basepath === 'index') { | |
basepath = '/' + baseparts.pop(); | |
if (basepath === '/controllers') { | |
basepath = ''; | |
} | |
} | |
else { | |
basepath = '/' + basepath; | |
} | |
var part = baseparts.pop(); | |
if (basepath && part !== 'controllers') { | |
basepath = '/' + part + basepath; | |
} | |
return basepath; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment