Hey there, I'm currently facing a challenge with retrieving the names of middleware functions in a specific request route. Let's consider the code snippet below as an example:
const authorizeRoute = (req,res,next) => {
let nextFunctionName = SomeFunctionToRetrieveTheNameOfTheNextMiddlewareToBeCalled()
if (isUserAuthorized(req.user.id, nextFunctionName)) next()
}
app.use(authorizeRoute)
app.get("/users", controller.getUsers)
app.get("/users/:id/posts", controller.getUserPosts)
In this scenario, I am aiming for the authorizeRoute
middleware to identify the name of the subsequent middleware function within the stack.
For instance, when a GET
request is made to "/users"
, I wish for the nextFunctionName
to hold the value of "getUsers"
or "controller.getUsers" or something similar.
Similarly, for a GET "/users/:id/posts"
request, I expect the nextFunctionName
to be set as "getUserPosts"
or equivalent.
Could you provide guidance on how to achieve this? I am relatively new to Express, Node.js, and JavaScript, so any assistance would be greatly appreciated.
I am aware that it is feasible to obtain the function name as a string in JavaScript.
someFunction.name // returns "someFunction" as a string
Hence, I believe that solving this challenge is possible. I just lack the knowledge of the precise approach to take.
P.S. While there may be alternate methods to attain the desired outcome, the example shared above resonates closely with my current requirements.