Skip to content

Instantly share code, notes, and snippets.

@damiancipolat
Created October 4, 2022 02:36
Show Gist options
  • Save damiancipolat/0a6adf45aecff136f0c536f9ecece800 to your computer and use it in GitHub Desktop.
Save damiancipolat/0a6adf45aecff136f0c536f9ecece800 to your computer and use it in GitHub Desktop.
Express JS - convert route list in tree
let route_list = {};
function print (path, layer) {
if (layer.route) {
layer.route.stack.forEach(print.bind(null, path.concat(split(layer.route.path))))
} else if (layer.name === 'router' && layer.handle.stack) {
layer.handle.stack.forEach(print.bind(null, path.concat(split(layer.regexp))))
} else if (layer.method) {
const pathRoute = `${layer.method.toUpperCase()} - ${path.concat(split(layer.regexp)).filter(Boolean).join('/')}`;
const base = pathRoute.split('/')[1];
if (route_list[base]){
if (!route_list[base].includes(pathRoute))
route_list[base].push(pathRoute);
}else{
route_list[base]=[pathRoute];
}
}
}
function split (thing) {
if (typeof thing === 'string') {
return thing.split('/')
} else if (thing.fast_slash) {
return ''
} else {
var match = thing.toString()
.replace('\\/?', '')
.replace('(?=\\/|$)', '$')
.match(/^\/\^((?:\\[.*+?^${}()|[\]\\\/]|[^.*+?^${}()|[\]\\\/])*)\$\//)
return match
? match[1].replace(/\\(.)/g, '$1').split('/')
: '<complex:' + thing.toString() + '>'
}
}
app._router.stack.forEach(print.bind(null, []))
console.log(JSON.stringify({
api:route_list
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment