Updating user information

We need an endpoint to update user information. We can define the endpoints by following these steps:

  1. Define the route in server/api/index.js:
routerAuth.put('/users/:id', User.update);
  1. Define the update method inside the user controller, server/api/user.js:
  update: (req, res) => {
Model.users
.updateData(
req.params.id,
req.body.user,
req.user.role === 'admin' || req.params.id === req.user.id,
req.user.role === 'admin',
)
.then(user => handleSuccess(res, { user }))
.catch(errors =>
handleFailure(res, { errors, message: errors.message,
status: 200 }),
);
},
  1. Define the updateData function inside the user model:
Schema.statics.updateData = function(
_id,
params = {},
permission = false,
isAdmin = false,
) {
return new Promise((resolve, reject) => {
try {
if (!permission) {
throw new Error('Permission denied');
}

this.findOne({ _id })
.then(user => {
if (!user) {
throw new Error('User not found');
}

const permitParams = Object.entries(params ||
{}).reduce(
(obj, [key, value]) =>
permitFields.includes(key) ? { ...obj, [key]: value
} : obj,
{},
);

if (!isAdmin) {
delete permitParams.role;
}

delete permitParams.email;

if (permitParams.password) {
permitParams.password = bcrypt.hashSync(
permitParams.password,
10,
);
}

return user.update(permitParams).then(() =>
this.findOne({ _id }));
})
.then(user => resolve(user.toJson()))
.catch(error => reject(error));
} catch (e) {
reject(e);
}
});
};

Test the endpoint using an HTTP client. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset