Home > Net >  Returning an array of middleware from another middleware in express JS?
Returning an array of middleware from another middleware in express JS?

Time:02-13

I have a route to view the information of a shop. The route looks like

router.param('userId',getUserById)
router.get("/store/:storeName/:userId?",isAuthenticated,getStoreDetail)

Based on the condition I want to send a response. In the route the userId is optional. If the userId is not provided it sends only particular information of the shop as a response. And if the userId is provided then I should authenticate the user and then send all the details of the shop.

So I created a middleware to achieve this.

const isAuthenticated = (req, res, next) => {
    const { user } = req
    if (user) {
        return [
            expressJwt(jwtTokenProperty),
            (err, req, res, next) => {
                if (err) {
                    return res.status(401).json({
                        status: false,
                        error: err.message,
                        isJWTError: true
                    })
                }
                const checker = req.user && req.auth && req.user.id == req.auth.id
                if (!checker) {
                    return res.status(401).json({
                        status: false,
                        error: "Invalid Request"
                    })
                }
                next()
            }
        ]
    } else {
        next()
    }
}

If the userId is not provided then I am getting a response as needed. But if the userId is provided I don't get any response.

CodePudding user response:

You forgot to return next().

Edit: You need to return a response rather than array containing a function.

const isAuthenticated = (req, res, next) => {
    const { user } = req
    return user
        ? [expressJwt(jwtTokenProperty), processResponse(err, req, res, next)]
        : next()
}

const processResponse = (err, req, res, next) => {
    if (err) {
        return res.status(401).json({
            status: false,
            error: err.message,
            isJWTError: true
        })
    }
    const checker = req.user && req.auth && req.user.id == req.auth.id
    if (!checker) {
        return res.status(401).json({
            status: false,
            error: "Invalid Request"
        })
    }
    return next()
}
  • Related