how to work with callback when calling Meteor methods? - meteor

I have noticed the callback functions never get executed all though the server method runs fine. Also from the Meteor documentation, i understand that when Meteor.Error is thrown it will notify the client but i don't see that working as well. Am i doing something fundamentally wrong?
Client
if (Meteor.isCordova) {
getContacts(function (contacts) {
$meteor.call('createContacts', contacts, function(err){
alert("in create contacts callback");
if(err && err.error === "not-logged-in"){
alert("error due to not-logged-in");
$ionicPopup.alert({
title: err.reason || "User not logged in",
template: 'Please try again after logged in',
okType: 'button-positive button-clear'
});
}
else if(err && err.error === "contacts-exists"){
$ionicPopup.alert({
title: err.reason || "Connections already exists",
template: 'Please try again after logged in',
okType: 'button-positive button-clear'
});
}
$meteor.call('createConnections');
});
});
}
function getContacts(success, error) {
function onSuccess(contacts) {
success && success(contacts);
};
var options = {};
options.multiple = true;
var fields = ["displayName", "name"];
navigator.contacts.find(fields, onSuccess, error, options);
}
Server
createContacts: function (contacts, callback) {
if (!this.userId) {
throw new Meteor.Error('not-logged-in',
'Must be logged in to update contacts')
}
var userId = this.userId, exist = Contacts.findOne({userId: userId});
log.debug("Is contacts for userId %s exist in database ? %s", userId, !! exist);
if (!exist) {
Contacts.insert({'userId': userId, 'contacts': contacts}, function () {
callback && callback();
});
} else {
log.debug("Contacts for user exists so throwing exception as contacts-exists");
var meteorErr = new Meteor.Error('contacts-exists', "Contacts are already exist");
callback && callback(meteorErr);
}
},

These callbacks are asynchronous. Your server-side method shouldn't invoke the callback function, nor even expect one as an argument.
You are right to pass the callback as the last argument to Meteor.call('createContacts'), but it is not up to the receiver of createContacts to determine when that callback should be invoked. In simple terms, from the client's point of view, the server's job is simply to return an 'OK' or an 'error' signal.
Remove any reference to the callback in the method definition (on the server), and expect the client to execute that callback when the server responds.
Try this:
Server
createContacts: function (contacts) {
if (!this.userId) {
throw new Meteor.Error('not-logged-in',
'Must be logged in to update contacts');
}
var userId = this.userId;
var exist = Contacts.findOne({userId: userId});
log.debug("Is contacts for userId %s exist in database ? %s", userId, !! exist);
if (!exist) {
Contacts.insert({'userId': userId, 'contacts': contacts});
} else {
log.debug("Contacts for user exists so throwing exception as contacts-exists");
throw new Meteor.Error('contacts-exists', "Contacts are already exist");
}
},
Client
$meteor.call('createContacts', contacts, function(err){
alert("in create contacts callback");
if(err && err.error === "not-logged-in"){
alert("error due to not-logged-in");
$ionicPopup.alert({
title: err.reason || "User not logged in",
template: 'Please try again after logged in',
okType: 'button-positive button-clear'
});
}
else if(err && err.error === "contacts-exists"){
$ionicPopup.alert({
title: err.reason || "Connections already exists",
template: 'Please try again after logged in',
okType: 'button-positive button-clear'
});
}
$meteor.call('createConnections');
});

Seems like i need to use .then() as documented in Angular-Meteor Document
Also changed the code as per amageddian

Related

socket.io get value that promise returns instead of promise { pending }

in socket.io i am trying to check if a user exist easily enough to where i can just call
if(checkUserExist(uid) == 'true'){
success();
}else{
failure();
};
so i figured out i need to use promises because the function i use to get info from the database is async so i do this
function checkUserExist(uid){
return new Promise(resolve => {
webUser.findOne({ _id: uid }, function(err, uid) {
if(uid){
console.log("USER EXISTS")
resolve('true')
}if(!uid){
console.log("USER NO REAL")
resolve('false')
}
})
});
and when i'm trying to use the function like this
socket.on('getAgents',function(uid){
console.log(checkUserExist(uid))
if(checkUserExist(uid) == 'true'){
console.log('user does exist getting agents')
agentList.find({}, function(err, docs) {
docs.forEach(function(d) {
socket.emit('newAgent', d.agentName)
});
});
}else if(checkUserExist(uid) == 'false'){
console.log('invalid uid ' + uid)
socket.emit('serverError', 'Invalid UID '+ uid)
}
})
the returned value is Promise { <pending> }
i am not sure what to do i thought that it was a simple enough task but obviously i don't yet know how to do it. is there anybody out there that can help me out.
promises is a fairly new concept to me and i still don't fully understand how they work should maybe use a library like promisify?
Thanks a ton :)
So, checkUserExist() returns a promise, not a value. That's how you coded it!
And, since the value is obtained asynchronously, you can't return the value directly anyway. See the canonical answer on that issue for more explanation on that topic.
To make your code work properly, you would have to actually use the promise that your function returns:
socket.on('getAgents',function(uid){
console.log(checkUserExist(uid))
checkUserExist(uid).then(result => {
if (result) {
agentList.find({}, function(err, docs) {
if (err) {
// decide what to do if there's a DB error here
return;
}
docs.forEach(function(d) {
socket.emit('newAgent', d.agentName)
});
});
} else {
socket.emit('serverError', 'Invalid UID ' + uid)
}
}).catch(err => {
socket.emit('serverError', 'Error processing UID ' + uid);
});
});

How to display ionic2 Alert after Firebase changeEmail

I have the following function to change the email on a Firebase user account. I want to display an ionic2 alert when complete, whether it was successful or there was an error. From my code below I do get the alert to display BUT it is blank. Most likely it is a timing issue on the Firebase promise but I don't know how to fix it.
private doChangeEmail(data): void {
var myAlert: {
title?: string,
subtitle?: string
} = {};
this.auth.ref.changeEmail({
oldEmail: data.oldemail,
newEmail: data.newemail,
password: data.password
}, function(error) {
if (error) {
switch (error.code) {
case "INVALID_PASSWORD":
myAlert.title = 'Invalid Password';
myAlert.subtitle = 'The specified user account password is incorrect.';
break;
case "INVALID_USER":
myAlert.title = 'Invalid User';
myAlert.subtitle = 'The specified user account does not exist.';
break;
default:
myAlert.title = 'Error creating user';
myAlert.subtitle = error;
}
} else {
myAlert.title = 'DONE';
myAlert.subtitle = 'User email changed successfully!';
}
});
let alert = Alert.create({
title: myAlert.title,
subTitle: myAlert.subtitle,
buttons: [{
text: 'OK',
handler: () => {
}
}]
});
this.nav.present(alert);
}
put the alert code inside the promise result....
this.auth.ref.changeEmail({
oldEmail: data.oldemail,
newEmail: data.newemail,
password: data.password
}, function(error) {
if (error){
// do error stuff..
} else {
// do success stuff..
}
// show alert here...
})
I found the following comment by Frank van Puffelen which solved my issue:
You're using this inside a callback function, where it has a different meaning. One solution is to use fat-arrow/rocket notation for the callback, which ensures this is what you expect it to be:
The correct syntax should be
this.auth.ref.changeEmail({
oldEmail: data.oldemail,
newEmail: data.newemail,
password: data.password
}, (error) => {
if (error){
// do error stuff..
} else {
// do success stuff..
}
// show alert here...
})
and the alert shows correclty as pointed out by Aaron Saunders

Accounts.createUser on server does not return response to client

I'm attempting to use Meteorjs Accounts on the server to create a new user and then send them an email to set their initial password. The idea is that an admin user can add new users.
I can successfully add the new user (I can see the new user ID in the server console if I log it), but that ID is never returned to the client. This is my server-side
Meteor.methods({
createNewUser: function(email){
return Accounts.createUser({email: email});
}
});
And the relevant client-side JS:
if (isNotEmpty(email) && isEmail(email)) {
Meteor.call("createNewUser", email, function(ret){
if (typeof ret.message !== 'undefined') {
if (ret.message === 'Email already exists. [403]') {
alert("exists");
} else {
alert("not created");
}
} else {
Accounts.sendEnrollmentEmail(ret, function(err){
if (err){
alert("email didn't get sent");
} else {
alert('success');
}
});
}
});
}
I get this in my browser console:
Exception in delivering result of invoking 'createNewUser': TypeError: Cannot read property 'message' of undefined
It's probably worth noting that I also get the "exists" alert if I try to submit the same email address twice in a row, so the error is getting returned to the client just fine.
The first argument in callback is always error object.
error equals null if everything is fine.
Meteor.call('createNewUser', email, function( error, result ){
if( error ){
console.error("ERROR -> ", error )
}else{
console.log("User was created!")
}
})
but that ID is never returned to the client.
Thats because you don't have any console.log on the client. also the meteor call look incorrect.
if (isNotEmpty(email) && isEmail(email)) {
Meteor.call("createNewUser", email, function(err,result){
if (typeof ret.message !== 'undefined') {
if (ret.message === 'Email already exists. [403]') {
alert("exists");
} else {
console.log(result) //here for example you should get the id
}
} else {
Accounts.sendEnrollmentEmail(ret, function(err){
if (err){
alert("email didn't get sent");
} else {
alert('success');
}
});
}
});
}

firebase executing method twice

I have set up a firebase simple login and its all working within my angular project. However for soem reason when ever I call the functions I have set up containing the login and createUser methods, they are called twice?
The controller is set up as follows:
angular.module('webApp')
.controller('AccountCtrl', function($scope, $window, $timeout) {
var ref = new Firebase('https://sizzling-fire-4246.firebaseio.com/');
and both methods are placed within my function straight from the firebase example on their website
When I press register, it will create the user and authenticate it, and then it will run again and tell me the email is taken.
I have checked with and without the timeouts and it still happens.
$scope.login = function(){
$scope.loginErrors = [];
$scope.loginSuccess = '';
var user = $scope.loginUser;
if(user.email === ''){
$scope.loginErrors.push('Please enter your email');
}
else if(user.password === ''){
$scope.loginErrors.push('Please enter your password');
}
else if(user.email === 'Admin'){
$window.location.href = '/#/admin';
} else {
ref.authWithPassword({
email : user.email,
password : user.password
}, function(error, authData) {
if (error) {
switch(error.code) {
case 'INVALID_EMAIL':
$scope.loginShow = true;
$timeout( function(){ $scope.loginMessage = 'Please enter a valid email address'; }, 500);
break;
case 'INVALID_USER':
$scope.loginShow = true;
$timeout( function(){ $scope.loginMessage = 'Please enter a valid user address'; }, 500);
break;
case 'INVALID_PASSWORD':
$scope.loginShow = true;
$timeout( function(){ $scope.loginMessage = 'Please enter the correct password'; }, 500);
break;
default:
console.log('error', error);
}
} else {
console.log('Authenticated successfully with payload:', authData);
$window.location.href = '/#/dashboard';
}
});
}
any help would be appreciated
I had a similar problem when developing and I had two browser tabs up running browser sync. Closed one and the problem went away.

Handlings exceptions on the server, customising the fail argument on the client

I'm hoping to be able to customise the error objects that are passed to the client if an exception occurs on the server.
I'm using the 'then' function on the client to handle success and failure:
hub.server.login(username, password).then(function(result) {
// use 'result'
}, function(error) {
// use 'error'
});
If the login succeeds, 'result' is the return value of the Login method on the server. If the login fails, I throw an exception of 'CustomException'. This is an exception with a 'Code' property.
if (!IsValidLogin(username, password))
throw new CustomException { Code: "BADLOGIN", Message: "Invalid login details" };
If I have detailed exceptions enabled, the 'error' argument on the client is 'Invalid login details' - the Message property of the exception.
Is there any way I can selectively change the error result from a string to a complex object? i.e. if 'CustomException' is thrown in a hub method, return a {Code:[...], Message:[...]} object for the client-side fail handler?
This should demonstrate what I'd like to see on the client:
hub.server.login(username, password).then(function(userInfo) {
alert("Hello " + userInfo.Name);
}, function(err) {
if (err.Code === "BADLOGIN.USERNAME")
alert("Unrecognised user name");
else if (err.Code === "BADLOGIN.PASSWORD");
alert("Invalid password");
else
alert("Unknown error: " + err.Message);
});
(Note the 'Code' and 'Message' properties on 'err').
When you call MapHubs with EnabledDetailedErrors set to true as follows:
RouteTable.Routes.MapHubs(new HubConfiguration { EnableDetailedErrors = true });
you will receive your Exception's Message string as the parameter to your fail handler.
I see that you have already figured this out, but I'm including the server side code to enable detailed errors for anyone else who might find this question later.
Unfortunately there is no easy way to send a complex object to the fail handler.
You could do something like this though:
if (!IsValidUsername(username))
{
var customEx = new CustomException { Code: "BADLOGIN.USERNAME", Message: "Invalid login details" };
throw new Exception(JsonConvert.SerializeObject(customEx));
}
if (!IsValidPassword(username, password))
{
var customEx = new CustomException { Code: "BADLOGIN.PASSWORD", Message: "Invalid login details" };
throw new Exception(JsonConvert.SerializeObject(customEx));
}
Then on the client:
hub.server.login(username, password).then(function(userInfo) {
alert("Hello " + userInfo.Name);
}, function(errJson) {
var err = JSON.parse(errJson);
if (err.Code === "BADLOGIN.USERNAME")
alert("Unrecognised user name");
else if (err.Code === "BADLOGIN.PASSWORD");
alert("Invalid password");
else
alert("Unknown error: " + err.Message);
});
I know this is ugly, but it should work.

Resources