How to read and append data to the json response object?

Hi everyone!

I am trying to write separate functions that add data to the json object that will be sent to the client. I would like to handle the response object directly in each of those functions, but when I use response.json() its previous value is overridden.

How can I build this json response object progressively from different functions?

can you share code that doesn’t work ?

I can’t share the exact code, but this shows what I’m looking for:

'use strict'

class UserController {

  checkCredentials(username, password, response) {
    // Get user with matching username and password
    // ...
    if (user) {
      return user
    } else {
      response.json({message: 'Invalid credentials'})
      throw new Error('LoginCredentialsError')
    }
  }

  checkBlockedUser(user, response) {
    // Do the blocked user checking
    // ...
    if (blockedUser) {
      response.json({message: 'Blocked user'})
      throw new Error('BlockedUserError')
    }
  }

  login({request, response}) {
    try {
      const { username, password } = request.post()
      const user = this.checkCredentials(username, password, response)
      this.checkBlockedUser(user, response)
      return {
        status: 'success',
        user: user
      }
    } catch (error) {
      // Here I'd like to access the set error values to do something
      // like
      let json = response.getJson()
      json.status = 'error'
      json = encrypt(json)
      return response.json(json)
    }
  }

}

module.exports = UserController

The important thing here, is what I’m trying to do in the catch section of the login method

I’d say, don’t pass the response into your checkCredentials & checkBlockedUser routines – you’re throwing what you need to know

then just return a 401 with a message

does that fit your needs?

  checkCredentials(username, password) {
    // Get user with matching username and password
    // ...
    if (user) {
      return user
    } else {
      throw new Error('Invalid credentials')
    }
  }

  checkBlockedUser(user) {
    // Do the blocked user checking
    // ...
    if (blockedUser) {
      throw new Error('Blocked user')
    }
  }
} catch (error) {
    response.status(401).send(`Authentication error: ${error.message}`);
}

I appreciate your advice, that is indeed a cleaner code. Since the response can have a wider range of statuses and optional data, my intention was to set that directly to response object in those simple handlers to manage the relative data of the response in each of them and to handle general data in a central piece of code. That’s why I was trying to make partial modifications directly to the intern response json object to be sent nevertheless it seems easier to use another object and later pass it to response.json()

1 Like