Created
July 7, 2018 20:13
-
-
Save chengjianhua/9094badc75a3b48df78134c13e0daf0f to your computer and use it in GitHub Desktop.
list-express-routes
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
/* eslint-disable no-underscore-dangle */ | |
function split(thing) { | |
if (typeof thing === 'string') { | |
return thing.split('/'); | |
} else if (thing.fast_slash) { | |
return ''; | |
} | |
const match = thing | |
.toString() | |
.replace('\\/?', '') | |
.replace('(?=\\/|$)', '$') | |
// eslint-disable-next-line no-useless-escape | |
.match(/^\/\^((?:\\[.*+?^${}()|[\]\\\/]|[^.*+?^${}()|[\]\\\/])*)\$\//); | |
return match | |
? match[1].replace(/\\(.)/g, '$1').split('/') | |
: `<complex:${thing.toString()}>`; | |
} | |
const buildIterator = () => { | |
const parsedRoutes = []; | |
const iterator = function iterator(path, layer) { | |
if (layer.route) { | |
layer.route.stack.forEach( | |
iterator.bind(null, path.concat(split(layer.route.path))) | |
); | |
} else if (layer.name === 'router' && layer.handle.stack) { | |
layer.handle.stack.forEach( | |
iterator.bind(null, path.concat(split(layer.regexp))) | |
); | |
} else if (layer.method) { | |
const parsedRoute = { | |
method: layer.method.toUpperCase(), | |
path: path | |
.concat(split(layer.regexp)) | |
.filter(Boolean) | |
.join('/'), | |
}; | |
parsedRoutes.push(parsedRoute); | |
} | |
}; | |
Object.assign(iterator, { parsedRoutes }); | |
return iterator; | |
}; | |
function listExpressRoutes(app) { | |
const iterator = buildIterator(); | |
app._router.stack.forEach(iterator.bind(null, [])); | |
const { parsedRoutes } = iterator; | |
return parsedRoutes.map(({ path, ...route }) => ({ | |
...route, | |
path: `/${path}`, | |
})); | |
} | |
module.exports = listExpressRoutes; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment