I have a rest api that receives a patch request with the following possible parameters:
- firstname
- lastname
- image
- birthday
If I receive the image parameter I will need to upload the image to a cdn and after that to update and save the user profile. If I don't receive the image parameter I will update and save the user profile.
What I had in mind was: if photo then upload -> promise -> update fields -> save else update fields -> save
My question: is there a best practice so I don't need to double a portion of code for each case?
app.patch('/users', authenticate, (req, res) => {
let body = _.pick(req.body, ['birthday', 'country', 'city', 'gender', 'firstname', 'lastname', 'photo']);
if ( body.photo ){
cloudinary.uploader.upload(body.photo,function(error, result) {
if( error ) {
res.status(400).send(error);
}
body.photo = result.url;
req.user = { ... req.user, ... body};
console.log ('update profile');
res.send(req.user);
});
}
req.user = { ... req.user, ... body};
console.log ('update profile');
res.send(req.user);
});