Hi,
I am adding a feature to a test app in meteor which allows admin users to edit other users details. I want to do this using a server method, so I can perform a bunch of validation (using meteor-roles package). I manage to patch a solution, but to me looks like quite a lot of code for something that should be simple. Can anyone take a look and point me in the right direction?
Here’s the server method:
Meteor.methods({
updateUser: function(targetUserId, fn, ln) {
check(targetUserId, String);
check(fn, String);
check(ln, String);
if (Roles.userIsInRole(Meteor.user(), ["admin"])) {
Users.update({
_id: targetUserId
}, {
$set: {
'profile.firstname': fn,
'profile.lastname': ln
}
})
} else throw new Meteor.Error(403, "Not authorized to create new users");
}
});
And here’s the client code (the form is in a modal dialog and the _id is stored in a Session variable):
var getEditedUser = function() {
var userId = Session.get('selectedUserId'),
user = Meteor.users.findOne({
_id: userId
})
return user;
};
Template.ModalEditClient.helpers({
user: getEditedUser
});
Template.ModalEditClient.events({
'click #saveEditUser': function(event, template) {
event.preventDefault();
var user = getEditedUser();
var firstname = template.find('#firstname').value;
var lastname = template.find('#lastname').value;
firstname = (firstname) ? firstname : user.profile.firstname;
lastname = (lastname) ? lastname : user.profile.lastname;
swal({
title: "Are you sure?",
text: "This will update user's details!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, update it!"
},
function() {
var userId = Session.get('selectedUserId')
Meteor.call('updateUser', userId, firstname, lastname, function(err, result) {
if (err) console.log(err)
});
$("#editUser").modal("hide");
});
}
});
Problems:
- I am doing tricks so I don’t update the user when data is not provided in the form, this is not really great.
- I am calling the Meteor.users.find() method twice, once for the template helper, once for getting the current user data in the event handler -> not optimal…
- I wanted to send a Javascript object to the update server method, but for some reason I am getting undefined when actually calling it…
I am pretty sure this can be done 1001 times more elegantly. Help?