How to perform an api call from a middleware in express – NodeJS

Issue

First of all, I’m working with express in NodeJS.
I want to create an API call for updating the user’s personal account informations.
Before doing this I should ask the user for the password for more security, this operation will be handled in this middleware isPasswordCorrect inside the request:

const isPasswordCorrect = (req, res, next) => {
    const password = req.password
    // perform the login call, to confirm the user identity
    // if password is correct call next()
}

I already created this endpoint to log in:

router.post('/login', (req, res) => {
    const { login, password } = req.body
    // do some logic for checking if the login data are correct
    res.json({"accessToken": accessToken})
})

So to facilitate the task, I want to call the above-mentionned login endpoint inside the middleware isPasswordCorrect, to check the identity of the user before updating his data

Solution

I would not do such an "internal API call", it will cause coupling between the APIs. As a result, the code is difficult to maintain.

I would create a repository or service layer to confirm the user identity.

E.g.

user-service.js

export const identifyUser = (password) => {
  // confirm the user identity
  // throw new Error('user identity error');
  return password
}

Then, in your middleware

const isPasswordCorrect = (req, res, next) => {
    try {
        userService.identifyUser(req.password)
        next()
    } catch (e) {
        next(e);
    }
}

Answered By – slideshowp2

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.