Home > Back-end >  Respond from controller method without express response
Respond from controller method without express response

Time:02-05

I'm trying to respond in case a fetch for an item doesn't return something from another method that doesn't have the express response. I call this method from another that if it has the express response:

const updateItem = async (req, res = response ) => {

    const id = req.params.id;
    const idItem = req.params.idItem; 

    await itemExists( id, idItem);

...

And in the itemExists() function I search for the item in mongo and if it doesn't exist I want to send it as a response but I don't know how to do it without using Express response:

const itemExists = async ( id, idItem ) => {

    const item = await PettyCashItems.findOne({ _id: id, "items._id": idItem });

    if (!item) {
        return ......
    }
}

Thanks.

CodePudding user response:

As already mentioned by one of the comments, there's no way to use response object without having access to it.

However, what you want can be achieved in two ways:

1- Easy way - return a value from itemExists function and send the response according to returned value from itemExists

const updateItem = async (req, res = response ) => {

    const id = req.params.id;
    const idItem = req.params.idItem; 

    const exists = await itemExists( id, idItem);

    if (exists) {
      res.send('YES')
      return;
    }

    res.send('NO');
}

2- Better way - Setup error handling for your express application so all thrown error are caught and response is sent based on the thrown error, then you can simply

class BaseHTTPException extends Error {
  constructor(statusCode) {
    super();
    this.statusCode = statusCode;
  }

}


class ItemDoesNotExistException extends BaseHTTPException {
  constructor() {
    super(400)
  }
}

throw new ItemDoesNotExistException()

in your itemExists function.

Further reading: https://expressjs.com/en/guide/error-handling.html

  •  Tags:  
  • Related