简体   繁体   中英

Looking for a way to destructure object and pass optional arguments to another method if they are exist

I want to make some properties optional and check whether propery exists and if it is I want to give it to this.UserService.update() method. I mean that i'm trying to update only those values which are passed to req.body.

user.controller.ts

private updateUser = async (
        req: Request,
        res: Response,
        next: NextFunction
    ): Promise<Response | void> => {
        try {
            const id = req.user.id;

            //I want to check every value below exist whether it exists
            const { old_password, name, email, password } = req.body;

            // Some of they may be empty and if some of them are not I want to give  
            // them to the method below
            const updatedUser = await this.UserService.update(id, /* here */);

            return res.status(200).json({ updatedUser });
        } catch (error: any) {
            next(new HttpException(400, error.message));
        }
    };

user.service.ts

public async update(
    id: string,
    old_password: string,
    name?: string,
    password?: string,
    email?: string
){}

You can directly check in update function:


public async update(
    id: string,
    old_password: string,
    name?: string,
    password?: string,
    email?: string
){
   if(name) {
       // Update name
   }
   if(email) {
       // Update email
   }
   // ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM