Is it possible to call a Method inside another Meteor.call? - meteor

I've got two methods on a same event click .open-message :
sendEmailContact : this method send a mail
openMessage : this method update the message (from new state to responded state)
The two methods are working fine, but separately.
My idea is to pass Meteor.call('sendEmailContact' and on success only, to pass Meteor.call('openMessage'
Below my current event & my unsuccess try
current event
Template.Users.events({
'click .open-message':function() {
Meteor.call('openMessage', this._id, function(error) {
if(error) {
Bert.alert({
title: 'Error',
message: error.reason,
type: 'danger'
});
} else {console.log ("ok");}
});
var to = this.email; // catch the to value
var contactmessage = this.message; // catch the original message
swal({
input: 'textarea',
title: "Response to " + to,
text: "H " + contactmessage,
type: "",
showCloseButton: true,
showCancelButton: true,
confirmButtonColor: "#272b35",
confirmButtonText: "Send"
}).then(function (text){
if(message != '') {
var from = "my#mail.com"
var subject = "Response to your message";
var message = text; //catch the value of the textarea
Meteor.call('sendEmailContact', to, from, subject, message, contactmessage, (error) => {
if(error) {
Bert.alert({
title: 'Error',
message: error.reason,
type: 'danger'
});
console.log (to);
console.log (from);
console.log (subject);
console.log (message);
} else {
console.log (to);
console.log (from);
console.log (subject);
console.log (message);
//target.text.value = ''; // Clear form
Bert.alert({
title: 'Success',
message: 'Message sended.',
type: 'success'
});
}
});
} else {
Bert.alert({
title: 'Error',
message: 'Message error.',
type: 'danger'
});
console.log (to);
console.log (from);
console.log (subject);
console.log (message);
}
}, function (dismiss) {
if (dismiss === 'cancel') {
null
//handle dismiss events like 'cancel', 'overlay', 'close', and 'timer'
}
})
}
});
unsuccess try (no error, the first method ok, but nothing on the second (console.log ("ok"); works))
Template.Users.events({
'click .open-message':function() {
var to = this.email; // catch the to value
var contactmessage = this.message; // catch the original message
swal({
input: 'textarea',
title: "Response to " + to,
text: "H " + contactmessage,
type: "",
showCloseButton: true,
showCancelButton: true,
confirmButtonColor: "#272b35",
confirmButtonText: "Send"
}).then(function (text){
if(message != '') {
var from = "my#mail.com"
var subject = "Response to your message";
var message = text; //catch the value of the textarea
Meteor.call('sendEmailContact', to, from, subject, message, contactmessage, (error) => {
if(error) {
Bert.alert({
title: 'Error',
message: error.reason,
type: 'danger'
});
console.log (to);
console.log (from);
console.log (subject);
console.log (message);
} else {
Meteor.call('openMessage', this._id, function(error) {
if(error) {
Bert.alert({
title: 'Error',
message: error.reason,
type: 'danger'
});
} else {console.log ("ok");}
});
console.log (to);
console.log (from);
console.log (subject);
console.log (message);
//target.text.value = ''; // Clear form
Bert.alert({
title: 'Success',
message: 'Message sended.',
type: 'success'
});
}
});
} else {
Bert.alert({
title: 'Error',
message: 'Message error.',
type: 'danger'
});
console.log (to);
console.log (from);
console.log (subject);
console.log (message);
}
}, function (dismiss) {
if (dismiss === 'cancel') {
null
//handle dismiss events like 'cancel', 'overlay', 'close', and 'timer'
}
})
}
});
EDIT
Below the two methods :
//Contact Method
Meteor.methods({
insertMessage: function(message) {
ContactMessages.insert(message);
},
openMessage: function(messageId) {
ContactMessages.update({_id: messageId}, {$set: {new: false, responded: true}});
},
deleteMessage: function(messageId) {
ContactMessages.remove({_id: messageId});
}
});
//Send ContactReply Method
Meteor.methods({
sendEmailContact: function(to, from, subject, message, contactmessage) {
check([to, from, subject, message, contactmessage], [String]);
// Let other method calls from the same client start running,
// without waiting for the email sending to complete.
this.unblock();
Email.send({
to: to,
from: from,
subject: subject,
text: message + contactmessage
});
}
});

You'll need to pass the messageId as an extra parameter to sendEmailContact from the client but then it should be pretty simple:
Meteor.methods({
insertMessage(message) {
ContactMessages.insert(message);
},
openMessage(messageId) {
ContactMessages.update(messageId, {$set: {new: false, responded: true}});
},
deleteMessage(messageId) {
ContactMessages.remove(messageId);
}
});
//Send ContactReply Method
Meteor.methods({
sendEmailContact(messageId,to, from, subject, message, contactmessage) {
check([messageId, to, from, subject, message, contactmessage], [String]);
this.unblock();
Email.send({
to: to,
from: from,
subject: subject,
text: message + contactmessage
});
Meteor.call('openMessage',messageId);
}
});
You don't even need a callback from the embedded Meteor.call() unless you want to log a potential error there.

in your 2nd example:
Meteor.call('openMessage', this._id, function(error) {
i think it doesn't know what "this" is.
so save it off at the top of the function and use the saved value through closure.
i'm also wondering why it's important that the client be the one to invoke both methods. it's technically possible to handle all that on the server; is that something that makes sense in your app?

Related

DynamoDb Update an Item from Node.js

I had the following code which originally worked for creating a user.
var params = {
TableName: 'myproject-user',
Item: {
id: req.body.userName,
email: req.body.email
}
};
if(req.body.currency) {
params.Item.currency = {
type: req.body.currency.type,
bank: req.body.currency.bank,
amount: req.body.currency.amount,
}
}
docClient.put(params, function(err, data) {
if (err) {
res.send({
success: false,
message: 'Error: ' + err
});
} else {
const { Items } = data;
res.send({
success: true,
message: 'Added user',
email: req.body.email
});
}
});
I'm now switching to put to update, as I want to be able to keep any existing values on the object while updating the email or name. In addition I have added the following line in the params object to specify the key which is id.
Key: { id : req.user.sub },
The doc.update code executes and I get back status 200 as if there was no problem, but when I look at the table the information hasn't been updated.
Do I need to use an expression or something to get update to work?
Code with changes:
var params = {
TableName: 'myproject-user',
Key: {"id":req.user.sub},
Item: {
id: req.body.userName,
email: req.body.email
}
};
docClient.update(params, function(err, data) {
if (err) {
res.send({
success: false,
message: 'Error: ' + err
});
} else {
const { Items } = data;
res.send({
success: true,
message: 'Added user',
email: req.body.email
});
}
});
I was able to get this working by using UpdateExpression, ExpressionAttributeValues, and ReturnValues attributes instead of Item, as described here:
var params = {
TableName: 'krncdev-user',
Key: {"id":req.user.sub},
UpdateExpression: "set email=:e",
ExpressionAttributeValues:{
":e": req.body.email
},
ReturnValues:"UPDATED_NEW"
};

Connecting peers doesn't work as expected - PeerJS

I am building audio calling application using PeerJS. In the call receiver, I have the following code inside peer.on('call', function(call) { ... }:
var conn = peer.connect(call.peer);
var receiveCall = bootbox.dialog({
className: "modal-danger nonumpad",
closeButton: false,
animate: true,
title: 'Call Recieved',
message: "Accept or Decline",
onEscape: null,
buttons: {
pickup: {
label: "<i class=\"fa fa-phone\"></i> Answer",
className: "btn-warning btn-lg pull-left",
callback: function(){
conn.send('ACCEPT') // send ACCEPT to the other client
window.currentCall = call;
call.answer(stream); // Answer the call with an A/V stream.
call.on('stream', function(remoteStream) {
var audio = $('<audio autoplay />').appendTo('body');
audio[0].src = (URL || webkitURL || mozURL).createObjectURL(stream);
});
return false;
}
},
hangup: {
label: "<i class=\"fa fa-phone\"></i> Decline",
className: "btn-warning btn-lg pull-left",
callback: function(){
conn.send('DECLINED') // send DECLINED to the other client
window.currentCall.close()
stream.getTracks().forEach(track => track.stop());
return false;
}
}
}
});
I can see the data is successfully received to the other client (the client who made the call). I am using the following code to receive the data:
callDialog.init(function(){
peer.on('connection', function(conn) {
conn.on('data', function(data){
console.log(call);
if(data == "ACCEPT"){
$("#test").text("This is dynamic msg");
$("#hangup").text("Hangup");
} else if (data == "DECLINED"){
stream.getTracks().forEach(track => track.stop());
}
});
});
});
The problem is here that I am using the same code in the client who is making the call to send data to the call receiver but it doesn't work and no error is showing in the console.
This is the code in the call initializer client:
var conn = peer.connect(destinationPeerId);
var callDialog = bootbox.dialog({
title: 'Making Call',
message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i><span id="test"> Waiting for Reply... </span></div>',
onEscape: null,
buttons: {
hangup: {
label: "<span id='hangup' <i class=\"fa fa-phone\"></i> Cancel </span>",
className: "btn-warning btn-lg pull-left",
callback: function(){
conn.send('DECLINED'); // sent to the call receiver
stream.getTracks().forEach(track => track.stop());
return false;
}
}
}
});
Why the same code sends data from the call receiver to the initializer, but not the other way around?
And how should I go with it to be able to send data the other way around?

Meteor.loginWithPassword() gives undefined

I'm currently working on a project to make a Pinterest clone in Meteor. The users need to fill in three test when they create an account, so I need to make a custom registration/login system. For now, I can create a new account, but when I want to log in with Meteor.loginWithPassword() nothing happens. Even no error or result.
Here's my code:
'submit .login-form': function(event){
event.preventDefault();
var emailVar = event.target.loginEmail.value;
var passwordVar = event.target.loginPassword.value;
console.log('here') // This is shown in the console
console.log(Meteor.loginWithPassword()) // gives undefined
Meteor.loginWithPassword(emailVar, passwordVar, function(err, suc) {
if (err) {
console.log(err); // This isn't shown in the console
} else {
console.log(succ); // This isn't shown in the console
Bert.alert({
title: "Welkom: " + Meteor.user().profile.name,
message: 'You're logged in!',
type: 'success',
style: 'growl-top-right',
icon: 'fa-check'
});
}
});
}
Edit:
As asked here's is the user in Meteor.users:
Image
And here are the strings that are filled in: Image
this should work:
'submit .login-form': function (event) {
event.preventDefault();
var emailVar = event.target.loginEmail.value;
var passwordVar = event.target.loginPassword.value;
Meteor.loginWithPassword(emailVar, passwordVar, function (err) {
if (!err) {
console.log("User logged in");
Bert.alert({
title: "Welkom: " + Meteor.user().profile.name,
message: "You're logged in !",
type: 'success',
style: 'growl-top-right',
icon: 'fa-check'
});
} else{
// Do something on error....
console.log("Not logged in, and error occurred:", err); // Outputs error
}
});
}

Need help updating Router.js for upgrade to Meteor 1.0 and iron:router package

I'm in the midst of updating from Meteor 8.2 to Meteor 1.0. I've removed all my old meteorite packages and installed the relevant meteor package system packages. I had to install the new iron-router package and I'm getting the following error in my console on meteor run:
Route dispatch never rendered. Did you forget to call this.next() in an onBeforeAction?
The migration notes for the package say: "onBeforeAction hooks now require you to call this.next(), and no longer take a pause() argument."
I tried following the example by remove pause from the function and adding this.next(); after the else statement, but to no avail.
How to edit my router so it uses the new onBeforeAction hook? Also, anything else you can call out from the migration that might be problematic would be much appreciated. Thanks!
Here's my router file:
/*****************************************************************************/
/* Client and Server Routes */
/*****************************************************************************/
// TODO: use these as per the Event Mind CLI tool.
//Router.configure({
// templateNameConverter: 'upperCamelCase',
// routeControllerNameConverter: 'upperCamelCase'
//});
Router.configure({
layoutTemplate: 'devLayout',
notFoundTemplate: 'devMain',
loadingTemplate: 'loading'
});
Router.onRun(function () {Session.set("waiting-on", null); });
Router.onBeforeAction(function() { Alerts.clearSeen(); });
var filters = {
nProgressHook: function (pause) {
// we're done waiting on all subs
if (this.ready()) {
NProgress.done();
} else {
NProgress.start();
pause(); // stop downstream funcs from running
}
}
};
Router.onBeforeAction(filters.nProgressHook);
Meteor.startup(function () {
Router.map(function () {
this.route('loading');
// reset password urls use hash fragments instead of url paths/query
// strings so that the reset password token is not sent over the wire
// on the http request
this.route('reset-password', {
template: 'devMain',
layoutTemplate: 'devLayout',
onRun: function () {
var token = this.params.hash;
Meteor.logout(function () {
Session.set("viewing-settings", true);
Session.set("set-password-token", token);
Session.set("settings-set-password", true);
// Session.set("enrolling", true) // do something special?
});
}
});
this.route('verify-email', {
template: 'devMain',
layoutTemplate: 'devLayout',
action: function () {
var self = this;
var token = self.params.hash;
Accounts.verifyEmail(token, function (err) {
if (!err) {
Alerts.throw({
message: "Your email address is now verified!",
type: "success", where: "main",
autoremove: 3000
});
Router.go('home');
} else {
Alerts.throw({
message: "Hmm, something went wrong: \""+err.reason +
"\". Try again?",
type: "danger", where: "main"
});
Session.set("viewing-settings", true);
Router.go('home');
}
});
}
});
this.route('leave-game', {
template: 'devMain',
layoutTemplate: 'devLayout',
action: function () {
var self = this;
var token = self.params.hash;
Meteor.call("leaveGameViaToken", token, function (err, res) {
if (!err) {
// Idempotently verify user's email,
// since they got the token via email.
Accounts.verifyEmail(token);
if (res.error) {
// e.g. "Leave-game link is for unknown game"
Alerts.throw({
message: res.error.reason, type: "danger", where: "main"
});
Router.go("home");
} else {
Alerts.throw({
message: "OK, you are no longer in this game.",
type: "success", where: res.gameId
});
Router.go("devDetail", {_id: res.gameId});
}
} else {
Alerts.throw({
message: "Hmm, something went wrong: \""+err.reason + "\".",
type: "danger", where: "main"
});
Router.go("home");
}
});
}
});
this.route('game-on', {
template: 'devMain',
layoutTemplate: 'devLayout',
action: function () {
var self = this;
var token = self.params.hash;
Meteor.call("gameOnViaToken", token, function (err, res) {
if (err || (res && res.error)) {
errorMessage = err ? "Hmm, something went wrong: \"" + err.reason + "\"." : res.error.reason;
Alerts.throw({
message: errorMessage, type: "danger", where: "main"
});
Router.go("home");
} else {
Alerts.throw({
message: "Woohoo! Players will be notified.",
type: "success", where: res.gameId
});
Router.go("devDetail", {_id: res.gameId, token: token });
}
});
}
});
this.route('cancel-game', {
template: 'devMain',
layoutTemplate: 'devLayout',
action: function () {
var self = this;
var token = self.params.hash;
Meteor.call("cancelGameViaToken", token, function (err, res) {
if (!err) {
Accounts.verifyEmail(token);
if (res.error) {
Alerts.throw({
message: res.error.reason, type: "danger", where: "main"
});
Router.go("home");
} else {
Alerts.throw({
message: "OK, your game is now cancelled, and players "
+ "will be notified.",
type: "success", where: "main"
});
Router.go("home");
}
} else {
Alerts.throw({
message: "Hmm, something went wrong: \""+err.reason + "\".",
type: "danger", where: "main"
});
Router.go("home");
}
});
}
});
// quite similar to 'leave-game' route
this.route('unsubscribe-all', {
template: 'devMain',
layoutTemplate: 'devLayout',
action: function () {
var self = this;
var token = self.params.hash;
Meteor.call("unsubscribeAllViaToken", token, function (err, res) {
if (!err) {
// Idempotently verify user's email,
// since they got the token via email.
Accounts.verifyEmail(token);
if (res.error) {
// e.g. "Token provided in link is not an unsubscribe-all token"
Alerts.throw({
message: res.error.reason, type: "danger", where: "main"
});
Router.go("home");
} else {
Alerts.throw({
message: "OK, you will no longer receive emails "
+ "from Push Pickup.",
type: "success", where: "main"
});
Router.go("home");
}
} else {
Alerts.throw({
message: "Hmm, something went wrong: \""+err.reason + "\".",
type: "danger", where: "main"
});
Router.go("home");
}
});
}
});
this.route('enroll-account', {
template: 'devMain',
layoutTemplate: 'devLayout',
onRun: function () {
var token = this.params.hash;
Meteor.logout(function () {
Session.set("viewing-settings", true);
Session.set("set-password-token", token);
Session.set("settings-set-password", true);
// Session.set("enrolling", true) // do something special?
});
}
});
// the home page. listing and searching for games
this.route('home', {
path: '/',
template: 'devMain',
layoutTemplate: 'devLayout'
});
// typical user interaction with a single game
this.route('devDetail', {
path: '/g/:_id/:token?',
layoutTemplate: 'devLayout',
onRun: function () {
Session.set("joined-game", null);
},
waitOn: function () {
return Meteor.subscribe('game', this.params._id);
},
onBeforeAction: function (pause) {
Session.set("soloGame", this.params._id);
},
data: function () {
var game = Games.findOne(this.params._id);
if (game) {
Session.set("gameExists", true);
}
return game;
},
action: function () {
var token = this.params.token;
if (Session.get("gameExists")) {
this.render();
} else {
Router.go('home');
Alerts.throw({
message: "Game not found",
type: "warning", where: "top"
});
}
if (token) {
Meteor.call("sendReminderEmailsViaToken", token, function (err, res) {
var errorMessage;
Accounts.verifyEmail(token);
if (err || (res && res.error)) {
errorMessage = err ? "Hmm, something went wrong: \"" + err.reason + "\"." : res.error.reason;
Alerts.throw({
message: errorMessage, type: "danger", where: "main"
});
Router.go("home");
}
});
}
},
onStop: function () {
Session.set("soloGame", null);
Session.set("gameExists", null);
}
});
this.route('devAddGame', {
path: '/addGame',
template: 'devEditableGame',
layoutTemplate: 'devLayout',
onRun: function () {
Session.set("selectedLocationPoint", null);
Session.set("newGameDay", null);
Session.set("newGameTime", null);
InviteList.remove({});
},
waitOn: function() {
Meteor.subscribe('recently-played');
},
data: function () {
return {
action: 'add',
title: 'Add game',
submit: 'Add game'
};
}
});
this.route('invitePreviousPlayers', {
path: 'invitePlayers',
template: 'invitePreviousPlayers',
layoutTemplate: 'devLayout'
});
this.route('devEditGame', {
path: '/editGame/:_id',
template: 'devEditableGame',
layoutTemplate: 'devLayout',
onRun: function () {
Session.set("selectedLocationPoint", null);
},
waitOn: function () {
return Meteor.subscribe('game', this.params._id);
},
onBeforeAction: function (pause) {
Session.set("soloGame", this.params._id);
},
data: function () {
return _.extend({
action: 'edit',
title: 'Edit game',
submit: 'Update game'
}, Games.findOne(this.params._id));
},
action: function () {
var self = this;
var user = Meteor.user();
var game = self.data();
if (user && user._id === game.creator.userId ||
user && user.admin) {
self.render();
} else {
Router.go('home');
}
}
});
this.route('adminView', {
path: '/admin',
onBeforeAction: function () {
var user = Meteor.user();
if (!user || !user.admin) {
this.render('home');
}
}
});
});
});
New onBeforeAction hook must call this.next(); You must call it in every onBeforeAction. For example your admin route in new Iron Router would look like this:
Router.route('/admin', {
name: 'adminView',
onBeforeAction: function () {
var user = Meteor.user();
if (!user || !user.admin) {
this.render('home');
}
this.next();
}
});
Replace all this.route(...) in Router.map with Router.route('/path', options) and remove Router.map()
Your global onBeforeAction will look like this:
Router.onBeforeAction(function() {
Alerts.clearSeen();
this.next();
});
Also, you don't need to wrap your routes in Meteor.startup(...). You can remove it.
And there is no pause parameter anymore, instead of pause call this.next() outside condition:
var filters = {
nProgressHook: function () {
// we're done waiting on all subs
if (this.ready()) {
NProgress.done();
} else {
NProgress.start();
}
this.next();
}
};
Router.onBeforeAction(filters.nProgressHook);

Meteor method not returning ID to client

I am in the process of integrating stripe payments on my website, but I have run into a problem.
I want to transition the user to a dynamic route upon submitting the payments form (iframe supplied by stripe), but the Meteor method that I call on the client returns undefined instead of the ID of the newly inserted document that I wish to transition to
Any advice?
ERROR
Error: Missing required parameters on path "/purchases/:purchaseId". The missing params are: ["purchaseId"]. The params object passed in was: undefined.
client:
Template.viewTab.events({
'click #download': function(event) {
handler.open({
name: 'Tabr',
description: this.title,
amount: this.price
});
event.preventDefault();
},
});
var handler = StripeCheckout.configure({
key: '..............',
token: function(token) {
// Use the token to create the charge with a server-side script.
// You can access the token ID with `token.id`
tabId = Tabs.findOne()._id;
Meteor.call('makePurchase', tabId, token, function(error, purchaseId) {
if (error) {
console.log('makePurchaseError: ' + error);
FlashMessages.clear();
return FlashMessages.sendError(error.message, {
autoHide: true,
hideDelay: 10000
});
}
console.log(purchaseId);
Router.go('viewPurchase', purchaseId);
});
}
});
Server:
Meteor.methods({
/**
* [makePurchase attempts to charge the customer's credit card, and if succesful
* it inserts a new purchaes document in the database]
*
* #return {[String]} [purchaseId]
*/
makePurchase: function(tabId, token) {
check(tabId, String);
tab = Tabs.findOne(tabId);
Stripe.charges.create({
amount: tab.price,
currency: "USD",
card: token.id
}, Meteor.bindEnvironment(function (error, result) {
if (error) {
console.log('makePurchaseError: ' + error);
return error;
}
purchaseId = Purchases.insert({
sellerId: tab.userId,
tabId: tab._id,
price: tab.price
}, function(error, result) {
if (error) {
console.log('InsertionError: ' + error);
return error;
}
return result;
});
}));
console.log(purchaseId);
return purchaseId;
}
});

Resources