2022-07-28

Getting name of current express middleware function

Long time reader first time question asker. My question is about dynamically accessing function names in express ^4.17.1. I have poured over both the internet and the express documentation with no luck.

I currently have input validation set up on all of my express middleware functions that ensures I'm getting the right information in the right format. When bad or incomplete information is given to a particular middleware I throw a nicely formatted error to the global error handler and I include the route that errored, the file in which the error occured, and the exact middleware in which it occured.

I've been able to dynamically retrieve both the route and the file name, but I'm having issues finding a way around hard coding in the name of the middleware. I can access the route stack and get the names of ALL middleware in the route, but there doesn't seem to be a way to determine which one you're in aside from keeping that list on res.locals and changing the array as you go (which isn't ideal). Here is a simple example of what I'm talking about.

const path = require("path");
const currFile = path.basename(__filename);

module.exports = {
  getStudentAssets(req, res, next) {
    const { studentName } = req.body;
    if (typeof studentName !== "string") {
      const iWouldLoveToGetThisDynamically = "getStudentAssets";
      const error = {
        status: 400,
        log: `ERROR on route ${req.originalUrl} in ${currFile} ${iWouldLoveToGetThisDynamically} middleware`,
      };
      return next(error);
    }
    // do random stuff
  },
};

I have a feeling there is a way to track which layer you're currently on as accessing req.route.stack looks something like this

[
  Layer {
    handle: [Function: getStudentAssets],
    name: 'getStudentAssets',
    params: undefined,
    path: undefined,
    keys: [],
    regexp: /^\/?$/i { fast_star: false, fast_slash: false },
    method: 'get'
  },
  Layer {
  // other middleware
  }
]

There has to be a way to identify which layer you're currently on, other than keeping a counter stored separately on res.locals that you update every middleware. If you've read this far thank you!



No comments:

Post a Comment