Christopher McCormack
Christopher McCormack

Reputation: 73

Passing Node.js middleware to a custom function

Question about express middleware. Say I have a route like the following:

router.route('/replies/:board')
    .post(bodyThreadIdVal, textVal, passVal, replyHandler.postReply)

Now let's say I wanted to move the first three middleware arguments from above out of the post method and into a custom method I created in another file, named postReply. How would I go about doing this? I thought maybe using app.use within my postReply method but not sure exactly how or if there is a cleaner way.

I have tried a few methods including

this.postReply = async (req, res, next) => {
    app.use(bodyThreadIdVal, textVal, passVal)(req, res, next)
    /* additional code */
}

But this seems to cause a recursive loop that rejects with Maximum call stack size exceeded

Upvotes: 2

Views: 113

Answers (1)

Volodymyr
Volodymyr

Reputation: 1408

If the only reason of moving middlewares into a sepparate file is groupping them in one place and making code cleaner and there is no necessity to create a function that will combine your middlewares then I would suggest to group such connected middlewares into an array:

const postReply = [bodyThreadIdVal, textVal, passVal];

router.route('/replies/:board')
    .post(...postReply, replyHandler.postReply);

If you will need to add some /* additional code */ just create a new middleware and add it to postReply array. This is definitely much cleaner way.

Upvotes: 1

Related Questions