2

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.