Angular client with signalR service not fire controller method - signalr

I have angular service where i got methods which are called from server when user connect or disconnect from my app
(function () {
//'use strict';
app.service('PrivateChatService', ['$rootScope', '$location', function PrivateChatService($rootScope, $location){
var online_users = [];
var proxy = $.connection.chatHub;
return {
addOnlineUser:
proxy.client.newOnlineUser = function (user) {
var newUser = ({
connectionId: user.ConnectionId,
UserName: user.UserName
});
online_users.push(newUser);
$.connection.hub.start()
},
removeOfflineUser: proxy.client.onUserDisconnected = function (id, user) {
var index = 0;
//find out index of user
angular.forEach(online_users, function (value, key) {
if (value.connectionId == id) {
index = key;
}
})
online_users.splice(index, 1);
$.connection.hub.start()
},
}
}])})();
Here i got controller method which i want to be fired when server calls newOnlineUser
PrivateChatService.newOnlineUser(function (user) {
$scope.online_users.push(newUser);
console.log("newOnlineUser finished");
});
So my question is. Is it possible to make with generated proxy or i have to use non-generated proxy access to those methods with which i am not very familiar.
With generated proxy as i show above it never reach my controller method to update my data in controller scope

Since nobody responded, what i find somehow odd. I found out this is working. I am not sure if this is good aproach since nobody answered and i didnt find any information how should this be solved.
app.service('PrivateChatService', ['$rootScope', '$location', function PrivateChatService($rootScope, $location){
var online_users = [];
var connection = $.hubConnection();
var proxy = connection.createHubProxy('chatHub');
function signalrCall(eventName, callback) {
proxy.on(eventName, function (user) {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(proxy, args)
})
});
connection.start();
}
return {
addOnlineUser: function (eventName, callback) {
signalrCall(eventName, callback);
},
getActiveUsers: function (eventName, callback) {
signalrCall(eventName, callback);
},
removeOfflineUser: function (eventName, callback) {
signalrCall(eventName, callback);
}
}
}])
angular controller methods
PrivateChatService.addOnlineUser("newOnlineUser", function (user) {
var newUser = ({
connectionId: user.ConnectionId,
UserName: user.UserName
});
$scope.online_users.push(newUser);
console.log("newOnlineUser finished");
});
PrivateChatService.getActiveUsers("getOnlineUsers", function (onlineUsers) {
angular.forEach($scope.online_users, function (scopeValue, scopeKey) {
//loop through received list of online users from server
angular.forEach(onlineUsers, function (serverListValue, serverListKey) {
if (!(serverListValue.ConnectionId == scopeValue.connectionId)) {
var newUser = ({
connectionId: serverListValue.ConnectionId,
UserName: serverListValue.UserName
});
$scope.online_users.push(newUser);
}
})
})
console.log("getOnlineUsers finished");
});
PrivateChatService.removeOfflineUser("onUserDisconnected", function (user) {
var index = 0;
//find out index of user
angular.forEach($scope.online_users, function (value, key) {
if (value.connectionId == user) {
index = key;
}
})
$scope.online_users.splice(index, 1);
});

Related

AWS Lambda Nodejs async.waterfall not executing MQTT Function

I am trying to use async.waterfall in the exports handler, and call functions sequentially. One of the function is related to MQTT message publishing. While the functions are being called, but when the MQTT function gets called, it just stops and not calls the require ('MQTT').
exports.handler = function(event, context) {
var async = require('async');
async.waterfall([
function(callback) {
retrieveEmailId(apiAccessToken,callback)
},
function(emailId, callback) {
retrieveDeviceDetails(callback)
},
function(deviceDetail, callback) {
publishMsg(callback)
}
], function(err, result) {
if (err) console.log('Error :: \n' + err);
});
}
function retrieveEmailId(accessToken, callback) {
var getEmailFromAlexaProfileObj = require('./GetEmailFromAlexaProfile');
getEmailFromAlexaProfileObj.doIt(accessToken, function(returnVal) {
console.log(returnVal);
callback(null, returnVal)
});
}
function retrieveDeviceDetails(callback) {
var getDevcieDetailsObj = require('./GetDevcieDetails');
getDeviceDetailsObj.doIt(null, function(returnVal) {
console.log(returnVal);
callback(null, returnVal)
});
}
function publishMsg() {
var mqtt = require('mqtt');
var options = {
clientId: "xxx",
username: "yyy",
password: "zzz",
clean: true
};
var client = mqtt.connect("mqtt://xxx.com", options)
client.on("connect", function () {
client.publish('xxx/yyy/L1', "1", options);
client.end();
});
}
Have you tried running the code locally using "lambda-local"? Does that sequence of call work along with the last one that is MQTT? What have you noticed when you invoke "require('mqtt')" within lambda?
Problem got resolved if the require variable is done prior to exports.handler.
for example....
var AWS = require('aws-sdk');
var async = require('async');
exports.handler = function(event, context) {
....
}

Using Meteor.wrapAsync to wrap a callback inside a method

This Meteor code is giving the error:
Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.
I tried Meteor.bindEnvironment for no avail and want to try Meteor.wrapAsync. I could not figure it out from the docs. Could some one please help me with the syntax? thx
Meteor.methods({
'createTransaction':
function (nonceFromTheClient, Payment) {
let user = Meteor.user();
gateway.transaction.sale(
{
arg_object
},
function (err, success) {
if (!err) {
//do stuff here
}
}
);
}
});
Wrap in Meteor.wrapAsync
Meteor.methods({
'createTransaction':
function (nonceFromTheClient, Payment) {
this.unblock();
let user = Meteor.user();
var sale = Meteor.wrapAsync(gateway.transaction.sale);
var res = sale({arg_object});
future.return(res);
return future.wait();
}
});
Or try wrapping it in Fiber
var Fiber = Npm.require('fibers');
Meteor.methods({
'createTransaction': function (nonceFromTheClient, Payment) {
Fiber(function() {
let user = Meteor.user();
gateway.transaction.sale(
{
arg_object
},
function (err, success) {
if (!err) {
//do stuff here
}
}
);
}).run()
}
});
Update: Here's how I handle stripe with Async.runSync and Meteor.bindEnvironment
var stripe = require("stripe")(Meteor.settings.private.StripeKeys.secretKey);
Meteor.methods({
'stripeToken': function() {
this.unblock();
var future = new Future();
var encrypted = CryptoJS.AES.encrypt(Meteor.userId(), userIdEncryptionToken);
future.return(encrypted.toString());
return future.wait();
},
'stripePayment': function(token) {
var userId = Meteor.userId();
var totalPrice = 0;
//calculate total price from collection
totalPrice = Math.ceil(totalPrice * 100) / 100;
userEmail = Meteor.users.findOne({
'_id': userId
}).emails[0].address;
// Create a charge: this will charge the user's card
var now = new Date();
Async.runSync(function(done) {
var charge = stripe.charges.create({
amount: Math.ceil(totalPrice * 100), // Amount in cents // coverting dollars to cents
currency: "usd",
source: token,
receipt_email: userEmail,
description: "Charging"
}, Meteor.bindEnvironment(function(err, charge) {
if (err) {
//handle errors with a switch case for different errors
done();
} else {
//handle res, update order
}
}));
}); // Async.runSync
},
});

Meteor.call and server methods not working properly

I have this code on my meteor app:
// client side
Template.lead.events({
'submit .insertExternalAccountForm': function (event) {
event.preventDefault();
Session.set('mcsStatus', 'Creating external account ...');
var target = {
code: event.target.code.value,
leadId: event.target.leadId.value,
name: event.target.name.value,
username: event.target.username.value,
password: event.target.password.value,
searchSourceId: event.target.searchSourceId.value,
clientId: event.target.clientId.value,
clientUserId: event.target.clientUserId.value
};
var noFormError = true;
if (target.username.length === 0) {
Session.set("username_error", "Field must not be empty");
noFormError = false;
} else {
Session.set("username_error", null);
}
if (target.password.length === 0) {
Session.set("password_error", "password must not be empty");
noFormError = false;
} else {
Session.set("password_error", null);
}
if (!noFormError) {
return noFormError;
}
Meteor.call('createExternalAccount', target, function (err, res) {
if (err) {
console.error(err);
}
console.log('in meteor call');
Router.go('/' + res.domain + '/' + res.externalId);
});
}
});
//server side
var createExternalAccountSync = function (query, external) {
return models.SearchSources.findOne(query).exec()
.then(function (searchsource) {
external.domain = searchsource.source;
var emr = searchsource.source.split('-');
return models.Organization.findOne({externalId: emr[2]}).exec();
}).then(function (org) {
console.log('after org');
external.organizationId = org._id;
return models.AppUser.findOne({clientId: external.clientId, externalId: external.clientUserId }).exec();
}).then(function (user) {
console.log('after app user');
external.userId = user._id;
external.userIds = [user._id];
return new Promise(function (resolve,reject) {
console.log('saveOrUpdate');
models.ExternalAccount.saveOrUpdate(external, function (err, newE) {
if (err) {
console.error(err)
reject(err);
}
resolve(newE)
});
});
})
.catch(function (e) {
console.error(e);
throw new Meteor.Error(e);
});
};
Meteor.methods({'createExternalAccount': function (data) {
var query = {};
var newExternalAccount = new models.ExternalAccount();
newExternalAccount.username = data.username;
newExternalAccount.password = data.password;
newExternalAccount.externalId = data.username;
newExternalAccount.name = data.name;
newExternalAccount.clientId = data.clientId;
newExternalAccount.clientUserId = data.clientUserId;
newExternalAccount._metadata = { leadId: data.leadId };
if (data.code === 'f') {
query.searchSourceId = '5744f0925db77e3e42136924';
} else {
query.searchSourceId = data.searchSourceId;
}
newExternalAccount.searchSourceId = query.searchSourceId;
console.log('creating external account')
createExternalAccountSync(query, newExternalAccount)
.then(function (external) {
console.log('should return to meteor call');
return external;
})
.catch(function (e) {
console.error(e);
throw new Meteor.Error(e);
});
}
});
The problem that I'm having is that the code on the server side, while it's being called properly, is not triggering the client side meteor.call, there's no console.log output or anything. I believe that the Meteor.wrapAsync method is properly used, but still not showing anything on the client side, and not in fact redirecting where I want the user to go after form submission.
UPDATE
The code has being updated to the newest form, but now I'm getting a weird error on the client, and its actually because the meteor.call method on the template returns neither error or result
Exception in delivering result of invoking 'createExternalAccount': http://localhost:3000/app/app.js?hash=c61e16cef6474ef12f0289b3f8662d8a83a184ab:540:40
http://localhost:3000/packages/meteor.js?hash=ae8b8affa9680bf9720bd8f7fa112f13a62f71c3:1105:27
_maybeInvokeCallback#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:3557:21
receiveResult#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:3577:30
_livedata_result#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:4742:22
onMessage#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:3385:28
http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:2736:19
forEach#[native code]
forEach#http://localhost:3000/packages/underscore.js?hash=27b3d669b418de8577518760446467e6ff429b1e:149:18
onmessage#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:2735:15
dispatchEvent#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:175:27
_dispatchMessage#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:1160:23
_didMessage#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:1218:34
onmessage#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:1365:28
By the code you provided,it could be because you are calling different method.
You defined 'createAccount' but on client side you are calling 'createExternalAccount'

Weird undefined error on server

I have the following meteor method
hasNoPendingPayments: function() {
var userId = Meteor.userId();
console.log(userId); <---------------------- correctly logs userId
var user = Users.findOne({_id: userId }, { fields: { services: 0 } });
console.log(user); <-------------------------- logs 'undefined'
return hasNoPendingPayments(user);
},
This private helper I call from the above
hasNoPendingPayments = function(user) {
// console.log('hasNoPendingPayments ');
// console.log(user);
var payments = Payments.find({ userId: user._id, status: {
$in: [Payments.States.PENDING, Payments.States.PROCESSING]}
});
return payments.count() === 0;
};
And I call it from the client here
Template.payments.created = function() {
this.hasNoPendingPayments = new ReactiveVar(false);v
};
Template.payments.rendered = function () {
Session.set('showPaymentRequestForm', false);
var self = this;
Meteor.call('hasNoPendingPayments', function(error, result) {
if (result === true) { self.hasNoPendingPayments.set(true); }
});
...
However, I get an undefined error on the server when I load the template initially (I marked where in code). Although, when I try call the same query on the client with the same userId, i correctly gets the user record
Any idea as to why this is?
Try with this.
Template.payments.rendered = function () {
Session.set('showPaymentRequestForm', false);
var self = this;
if(Meteor.userId()){
Meteor.call('hasNoPendingPayments', function(error, result) {
if (result === true) { self.hasNoPendingPayments.set(true); }
});
}else{
console.log("Seems like user its not logged in at the moment")
}
Maybe when you make the Meteor.call, the data its not ready
Also just to be sure, when you run Users.findOne({_id: userId }, { fields: { services: 0 } }); on console.log what you get?
Maybe the find is wrong or have some typo
update
Router.map(function()
{
this.route('payments',
{
action: function()
{
if (Meteor.userId())
this.render();
} else{
this.render('login') // we send the user to login Template
}
}
}
or waitOn
Router.map(function () {
this.route('payments', {
path: '/payments',
waitOn: function(){
return Meteor.subscribe("userData"); //here we render template until the subscribe its ready
}
});
});
Meteor stores all the user records in Meteor.users collection
so try Meteor.users.findOne({_id: userId }....)
Instead of Users.findOne({_id: userId }, { fields: { services: 0 } });
in your server method

return values from server side meteor methods

Here is my code,
googleContacts:function()
{
var opts= { email: Meteor.user().services.google.email,
consumerKey: "xxxxxxxx",
consumerSecret: "xxxxxxxxxx",
token: Meteor.user().services.google.accessToken,
refreshToken: Meteor.user().services.google.refreshToken};
gcontacts = new GoogleContacts(opts);
gcontacts.refreshAccessToken(opts.refreshToken, function (err, accessToken)
{
if(err)
{
console.log ('gcontact.refreshToken, ', err);
return false;
}
else
{
console.log ('gcontact.access token success!');
gcontacts.token = accessToken;
gcontacts.getContacts(function(err, contact)
{
console.log(contact);
return contact;//want to return this value
})
}
});
}
I want to return the contact to the called method,as it is in a inner function i'm getting a bit difficult to return it to the called method.If it is in client side,then we can store the value in a session variable and we can return that,but this is a server side method,How to do this?
Use Futures:
Future = Npm.require('fibers/future');
Meteor.methods({
methodname: function() {
var fut = new Future();
apiCall(function(err, res) {
fut.return(...);
});
return fut.wait();
},
});

Resources