Home > Back-end >  Respond from method in controller without req, res from Express
Respond from method in controller without req, res from Express

Time:01-28

I have a method that performs an update in Mongo but I do not have access to "res" and "res" since it is a method that I will use on more than one occasion.

My problem is when responding to the update as I try with a return but it doesn't work as the request never completes. Do you know how I can answer then?

This method calls the method that will be reused several times:

let item = (req, res = response ) => {

        const { id } = req.params;
    
        const { status, user, ...data } = req.body; 
        data.user = req.uid; 
        data.expenditure = null;

        let item = {
                concept: data.concept,
                revenue: data.revenue,
            'createdBy': {
                    uid: req.uid,
                    username: req.user.username,
                },
                description: data.description
         }
            
        createNewItem( id, item );
}

And this is the method to reuse several times that does not have "req" or "res":

const createNewItem = async ( id, item ) => {

       try {

        let pettycash = await PettyCash.findByIdAndUpdate( id,
            {
                $push: { 
                    'items': {
                      $each: [item],
                    }
                }
            },{ new: true }

        );

    return { err: null, status: 200, pettycash };
        
             
    } catch (err) {
        return { err: err.toString(), status: 500, data: null };         
    } 
}

Although the process is correct return { err: null, status: 200, pettycash }; doesn't finish the request so POSTMAN never finishes and you keep waiting for some response.

Thanks.

CodePudding user response:

Okay so two options.

One pass res to function as argument which you don't want and is not a good idea because it violates single responsibility rule for a function.

You add await so that controller waits for the function execution to complete. To do this make your controller async. This is generally a good idea. You let controller do its work meanwhile your createNewItem only have single responsibility of creating an item.

let item = async (req, res = response ) => {

    const { id } = req.params;

    const { status, user, ...data } = req.body; 
    data.user = req.uid; 
    data.expenditure = null;

    let item = {
            concept: data.concept,
            revenue: data.revenue,
        'createdBy': {
                uid: req.uid,
                username: req.user.username,
            },
            description: data.description
     }
        
    await createNewItem( id, item );

    // send response back
 }
  •  Tags:  
  • Related