0

Node.js pratics

I am not sure if I am using .then() and .catch() functions on the right way you can find my code below of a login function. Could you tell me if this code is ok or if it's a bad pratic? I didn't find code like mines on the web that's why I ask and I am worry.... If it's a bad pratic, how to right this code on the right way ? Thank you by advance :)

const login = (request, response) => {
  // user login informations
  const user = {
    email: request.body.email,
    password: request.body.password
  }
  // check if there is erros in datas
  const { valid, errors } = validateLoginDatas(user)
  if (!valid) {
    return response.status(400).json(errors)
  }
  // firebase authentification
  firebase.auth().signInWithEmailAndPassword(user.email, user.password)
    .then(() => {
      // we create an access token and save it in db, it will be util to refresh the access token when it will expire
      const refreshToken = crypto.randomBytes(128).toString('base64')
      getUserIdByEmail(user.email)
        .then((idUser) => {
          // update of the refreshToken
          upsertUserRefreshToken(idUser, refreshToken)
          getUserRoleWithId(idUser)
            .then((role) => {
              // new accessToken with id_user and user's role inside
              const accessToken = jwt.sign(
                {
                  idUser: idUser,
                  role: role
                },
                jwtConfig.secretKey,
                {
                  algorithm: jwtConfig.algorithm,
                  expiresIn: jwtConfig.expiresIn
                }
              )
              return response.json({ accessToken })
            })
            .catch((error) => {
              return response.status(403).json({ error: error.message })
            })
        })
        .catch((error) => {
          return response.status(403).json({ error: error.message })
        })
    })
    .catch((error) => {
      if (error.code === 'auth/wrong-password') {
        return response.status(403).json({ general: 'Wrong credentials, please try again' })
      }
      return response.status(500).json({ error: error.code })
    })
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Carlos
  • 119
  • 10
  • 2
    Imbricate? Do you mean nest? If so, yes, you probably should [unnest them and chain instead](https://stackoverflow.com/a/22000931/1048572) – Bergi Oct 24 '20 at 23:46
  • consider rewriting it using `async/await` – noseratio Oct 25 '20 at 00:11
  • I think if you chain them, you will also want to add a second argument to some or all of your `.then` calls. This is a function to handle the situation in which the promise rejects at this stage in the chain. This replaces the `.catch` that follows each of your nested `.then`s. You won't need this `onRejected` handler in every case, but you should know how to include it when you do. (See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) – Cat Oct 25 '20 at 00:31

0 Answers0