Last active
August 29, 2015 14:02
-
-
Save totherik/9a8c6b881ca8dc77f51f to your computer and use it in GitHub Desktop.
Crawl express 4.x application to build middleware structure and route mappings.
This file contains 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
'use strict'; | |
/** | |
* In order for this to work correctly, `this.path = path;` needs to be added in | |
* the Layer constructor function here: | |
* https://github.com/visionmedia/express/blob/7df7f7a575df4cf26c1d43535a6a1a6b8778933c/lib/router/layer.js#L21 | |
*/ | |
module.exports = function crawl(obj, path, tree) { | |
path = path || ''; | |
tree = tree || {}; | |
if (obj._router) { | |
// obj is application | |
path = path || obj.get('mountpath'); | |
crawl(obj._router, path, tree); | |
} else if (Array.isArray(obj.stack)) { | |
// obj is application or Route | |
// both have the `stack` property | |
obj.stack.forEach(function (handler) { | |
crawl(handler, path, tree); | |
}); | |
} else if (typeof obj.stack === 'function') { | |
// TODO: Is this really a thing still? | |
crawl(obj.stack, path, tree); | |
} else if (obj.route) { | |
// obj is Layer | |
// obj.route is Route, which has the necessary `path` property. | |
crawl(obj.route, path + (obj.route.path || ''), tree); | |
} else if (obj.handle) { | |
// obj is either a Layer or a special object. TBD | |
if (obj.method) { | |
// Special object in express/lib/router/route.js | |
// @see https://github.com/visionmedia/express/blob/4638883f0d943b551c60862161e1488e9c150297/lib/router/route.js#L164 | |
path = path || '(all)'; | |
if (path[path.length - 1] === '/') { | |
path = path.slice(0, -1); | |
} | |
path = path || '/'; | |
tree[path] = tree[path] || {}; | |
tree[path][obj.method] = tree[path][obj.method] || []; | |
tree[path][obj.method].push(obj.handle.name || '(anonymous)'); | |
} else { | |
// obj is Layer or special object (still) | |
// @see https://github.com/visionmedia/express/blob/4638883f0d943b551c60862161e1488e9c150297/lib/router/route.js#L140 | |
if (obj.path) { | |
// It's a Layer | |
path += obj.path; | |
} | |
// obj.handle is Function | |
crawl(obj.handle, path, tree); | |
} | |
} else { | |
path = path || '(all)'; | |
tree[path] = tree[path] || []; | |
tree[path].push(obj.name || '(anonymous)'); | |
} | |
return tree; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment