Skip to content

Instantly share code, notes, and snippets.

@ErisDS
Last active April 24, 2020 15:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ErisDS/2fec0b64f28a945cb8d4 to your computer and use it in GitHub Desktop.
Save ErisDS/2fec0b64f28a945cb8d4 to your computer and use it in GitHub Desktop.
Print an express middleware stack
module.exports = function stackPrinter(req, res, next) {
console.log('Printing Stack For', req.url);
function printItem(item, prefix) {
prefix = prefix || '';
if (item.route) {
console.log(prefix, 'Route', item.route.path);
} else if (item.name === '<anonymous>') {
console.log(prefix, item.name, item.handle);
} else {
console.log(prefix, item.name, item.method ? '(' + item.method.toUpperCase() + ')' : '');
}
printSubItems(item, prefix + ' -');
}
function printSubItems(item, prefix) {
if (item.name === 'router') {
console.log(prefix, 'MATCH', item.regexp);
if (item.handle.stack) {
item.handle.stack.forEach(function (subItem) {
printItem(subItem, prefix);
});
}
}
if (item.route && item.route.stack) {
item.route.stack.forEach(function (subItem) {
printItem(subItem, prefix);
});
}
if (item.name === 'mounted_app') {
console.log(prefix, 'MATCH', item.regexp);
}
}
req.app._router.stack.forEach(function(stackItem) {
printItem(stackItem);
});
next();
});
@csyouk
Copy link

csyouk commented Apr 24, 2020

Could u write some example for this middleware script?

@csyouk
Copy link

csyouk commented Apr 24, 2020

Ah! I solved it. For people who drop by this script.

  app.get('/api/blogs', requireLogin, stackPrinter, async (req, res) => {
    const blogs = await Blog
      .find({ _user: req.user.id })
      .cache({
        key: req.user.id
      });
    res.send(blogs);
  });

Results :

[0]  Printing Stack For /api/blogs
[0]  query 
[0]  expressInit 
[0]  jsonParser 
[0]  _cookieSession 
[0]  initialize 
[0]  authenticate 
[0]  Route /auth/google
[0]  - authenticate (GET)
[0]  Route /auth/google/callback
[0]  - authenticate (GET)
[0]  - <anonymous> [Function]
[0]  Route /auth/logout
[0]  - <anonymous> [Function]
[0]  Route /api/current_user
[0]  - <anonymous> [Function]
[0]  Route /api/blogs/:id
[0]  - <anonymous> [Function]
[0]  - <anonymous> [AsyncFunction]
[0]  Route /api/blogs
[0]  - <anonymous> [Function]
[0]  - stackPrinter (GET)
[0]  - <anonymous> [AsyncFunction]
[0]  Route /api/blogs
[0]  - <anonymous> [Function]
[0]  - <anonymous> [AsyncFunction]
[0]  - <anonymous> [AsyncFunction]
[0]  Route /api/upload
[0]  - <anonymous> [Function]
[0]  - <anonymous> [Function]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment