I've written up a Parse Cloud script in JS which gets called in my Objective-C app. When the script gets called I get an error with the code: 141.
Here is the code, it gets called when a user accepts a friend request from another user (I'm also not entirely familiar with JS either):
Parse.Cloud.define("addFriendToFriendsRelation", function(request, response) {
Parse.Cloud.useMasterKey();
var friendRequestId = request.params.friendRequest;
var query = new Parse.Query("FriendRequest");
//get the friend request object
query.get(friendRequestId, {
success: function(friendRequest) {
//get the user the request was from
var fromUser = friendRequest.get("from");
//get the user the request is to
var toUser = friendRequest.get("to");
var relation = fromUser.relation("friends");
//add the user the request was to (the accepting user) to the fromUsers friends
relation.add(toUser);
//save the fromUser
fromUser.save(null, {
success: function() {
//saved the user, now edit the request status and save it
friendRequest.set("status", "accepted");
friendRequest.save(null, {
success: function() {
response.success("saved relation and updated friendRequest");
},
error: function(error) {
response.error(error);
}
});
},
error: function(error) {
response.error(error);
}
});
},
error: function(error) {
response.error(error);
}
});
});
All help and suggestions are greatly appreciated. Thank you.
EDIT: In my code I am calling:
[PFCloud callFunctionInBackground:#"addFriendToFriendsRelation" withParameters:#{#"friendRequest" : friendRequest.objectId} block:^(id object, NSError *error) {
EDIT2: The error I am getting in the JS script is the last
error: function(error) {
response.error(error);
}
to be called.
This will solve your problem , all you have to do is
add
useMasterKey: true
in the find method.
change your code to this
Parse.Cloud.define("addFriendToFriendsRelation", function(request, response) {
Parse.Cloud.useMasterKey();
var friendRequestId = request.params.friendRequest;
var query = new Parse.Query("FriendRequest");
//get the friend request object
query.get(friendRequestId, {
useMasterKey: true, success: function(friendRequest) {
//get the user the request was from
var fromUser = friendRequest.get("from");
//get the user the request is to
var toUser = friendRequest.get("to");
var relation = fromUser.relation("friends");
//add the user the request was to (the accepting user) to the fromUsers friends
relation.add(toUser);
//save the fromUser
fromUser.save(null, {
success: function() {
//saved the user, now edit the request status and save it
friendRequest.set("status", "accepted");
friendRequest.save(null, {
success: function() {
response.success("saved relation and updated friendRequest");
},
error: function(error) {
response.error(error);
}
});
},
error: function(error) {
response.error(error);
}
});
},
error: function(error) {
response.error(error);
}
});
});
Related
I want to add users to my Parse.Role but it's not working. I looked at a number of examples and they all seem pretty straight-forward however I'm unable to get it right. Here is my code:
Parse.Cloud.define("activateVendor", function(request, response){
var query = new Parse.Query(Parse.Role);
query.equalTo("name", "vendor");
query.first ({
success: function(role) {
role.getUsers().add(request.params);//request.params is the parse object, should I be using request.params.id?
role.save();
},
error: function(error) {
throw "Got an error " + error.code + " : " + error.message;
}
})
});
It depends on who you wish added to the role. The user who made the cloud request is available via the request object...
role.getUsers().add(request.user);
Otherwise, you can get a user via a query as #RobertRowntree suggests. (though, I'd suggest doing it with promises).
does what you want with 2 queries (Role, User) ...
var qu = new Parse.Query(Parse.User);
var qr = new Parse.Query(Parse.Role);
Parse.Cloud.useMasterKey();
qr.get(roleId, {
success: function(role) {
_role = role;
qu.get(userId, {
success: function(user) {
_role.getACL().setRoleReadAccess(_role, true);
_role.getUsers().add(user);
_role.save();
response.success(_role.toJSON());
},
error: function(object, error) {
}
});
},
error: function(object, error) {
}
});
I have an App using Parse.com as a backend and an external site that acts as my payment gateway. Upon receiving the customer/subscription webhook data from Stripe I wish to lookup the users email so I can then run a Cloud Code function and change their user status to 'paid'
My webhook receiver is:
Parse.Cloud.define("update_user", function(request, response) {
var data = request.params["data"]
var customer = data.object.customer;
response.success'Working' + request);
});
And I am able to get an email back from stripe from the customer ID using:
Parse.Cloud.define("pay", function(request, response) {
Stripe.initialize(STRIPE_SECRET_KEY);
console.log(JSON.stringify(request.params));
Stripe.Customers.retrieve(
customerId, {
success:function(results) {
console.log(results["email"]);
// alert(results["email"]);
response.success(results);
},
error:function(error) {
response.error("Error:" +error);
}
}
);
});
I need help turning this into a complete function that is run on receipt of every webhook from Stripe. I am also struggling with options for fallback if this does not work for whatever reason.
EDIT
Taking parts of the first answer and I now have:
Parse.Cloud.define("update_user", function(request, response) {
Stripe.initialize(STRIPE_SECRET_KEY);
var data = request.params["data"]
var customerId = data.object.customer;
get_stripe_customer(customerId, 100).then(function(stripeResponse) {
response.success(stripeResponse);
}, function(error) {
response.error(error);
});
});
function get_stripe_customer (customerId) {
Stripe.initialize(STRIPE_SECRET_KEY);
return Stripe.Customers.retrieve(
customerId, {
success:function(results) {
console.log(results["email"]);
},
error:function(error) {
}
}
);
};
My knowledge is really falling down on the Promise side of things and also the callback (success:, error, request response) etc further reading would be appreciated.
This is now working
Out of interest I did this:
Parse.Cloud.define("update_user", function(request, response) {
var data = request.params["data"]
var customerId = data.object.customer;
get_stripe_customer(customerId, 100).then(function(stripeResponse) {
return set_user_status(username, stripeResponse);
}).then(function(username) {
response.success(username);
}, function(error) {
response.error(error);
});
});
function get_stripe_customer (customerId) {
Stripe.initialize(STRIPE_SECRET_KEY);
return Stripe.Customers.retrieve(
customerId, {
success:function(results) {
// console.log(results["email"]);
},
error:function(error) {
}
}
);
};
function set_user_status(stripeResponse) {
Parse.Cloud.useMasterKey();
var emailquery = new Parse.Query(Parse.User);
emailquery.equalTo("username", stripeResponse['email']); // find all the women
return emailquery.first({
success: function(results) {
alert('running set_user_status success');
var user = results;
user.set("tier", "paid");
user.save();
},
error:function(error) {
console.log('error finding user');
}
});
};
open to improvements...
EDIT - I (#danh) cleaned it up a bit. A few notes:
used promises throughout. much easier to read and handle errors
get_stripe_customer requires only one param (that 100 was my idea to charge $100)
set_user_status appears to need only user email as param, which apparently is in the stripeResponse
set_user_status returns a promise to save the user. that will be fulfilled with the user object, not the username
be sure you're clear on how to identify the user. stripe apparently provides email address, but in your user query (in set_user_status) you compare email to "username". some systems set username == email. make sure yours does or change that query.
Parse.Cloud.define("update_user", function(request, response) {
var data = request.params["data"]
var customerId = data.object.customer;
get_stripe_customer(customerId).then(function(stripeResponse) {
var email = stripeResponse.email;
return set_user_status(email);
}).then(function(user) {
response.success(user);
}, function(error) {
response.error(error);
});
});
function get_stripe_customer(customerId) {
Stripe.initialize(STRIPE_SECRET_KEY);
return Stripe.Customers.retrieve(customerId).then(function(results) {
// console.log(results["email"]);
return results;
});
};
function set_user_status(email) {
Parse.Cloud.useMasterKey();
var emailquery = new Parse.Query(Parse.User);
emailquery.equalTo("username", email); // find all the women
return emailquery.first().then(function(user) {
user.set("tier", "paid");
return user.save();
}, function(error) {
console.log('error finding user ' + error.message);
return error;
});
}
Did a quick skim of the docs pertaining to stripe, and it looks like the steps are: (1) make a stripe REST-api call from your client side to get a token, (2) pass that token to a cloud function, (3) call stripe from the parse cloud to finish paying. I understand that you'd like to include a (4) fourth step wherein the transaction is recorded in the data for the paying user.
From the client (assuming a JS client):
var token = // we've retrieved this from Stripe's REST api
Parse.Cloud.run("pay", { stripeToken: token }).then(function(result) {
// success
}, function(error) {
// error
});
On the server:
Parse.Cloud.define("pay", function(request, response) {
var user = request.user;
var stripeToken = request.params.stripeToken;
payStripeWithToken(stripeToken, 100).then(function(stripeResponse) {
return updateUserWithStripeResult(user, stripeResponse);
}).then(function(user) {
response.success(user);
}, function(error) {
response.error(error);
});
});
Now we need only to build promise-returning functions called payStripeWithToken and updateUserWithStripeResult.
// return a promise to pay stripe per their api
function payStripeWithToken(stripeToken, dollarAmt) {
Stripe.initialize(STRIPE_SECRET_KEY); // didn't see this in the docs, borrowed from your code
return Stripe.Charges.create({
amount: dollarAmt * 10, // expressed in cents
currency: "usd",
card: stripeToken //the token id should be sent from the client
});
// caller does the success/error handling
}
// return a promise to update user with stripeResponse
function updateUserWithStripeResult(user, stripeResponse) {
var transactionId = // dig this out of the stripeResponse if you need it
user.set("paid", true);
user.set("transactionId", transactionId);
return user.save();
}
Any ideas why this isn't working? It comes back with the success message but doesn't actually update anything.
I'm adding an FB user using Parse but since it doesn't have a func to add the username and email trying to do it this way. Any help much appreciated.
JS
Parse.Cloud.run("test", { objectId: "Q8XRUcL22N", name: "Rich", email: "rich#gmail.com"}, {
success: function(results) {
console.log(results);
},
error: function(error) {
console.log(error);
}
});
CLOUD CODE:
Parse.Cloud.define("test", function (request, response) {
Parse.Cloud.useMasterKey();
var uid;
var query = new Parse.Query("_User");
query.count({
success: function (results) {
uid = parseInt(results);
},
error: function () {
response.error("UID lookup failed");
}
});
var query = new Parse.Query(Parse.User);
query.equalTo("objectId", request.params.objectId);
query.first({
success: function (object) {
object.set("username", request.params.name);
object.set("email", request.params.email);
object.set("uid", uid);
var acl = new Parse.ACL();
acl.setPublicWriteAccess(false);
acl.setPublicReadAccess(false);
object.setACL(acl);
object.save();
response.success("Success Message");
},
error: function (error) {
response.error("Error Message");
}
});
});
Thanks
Calling success() or error() on the response halts whatever is underway at the time, including the save() on the user.
Also, it looks like you want to record in the user a count of users at the time the ACL is set. Getting the count must also be serialized with the other operations. (Also, please note that count is only good as an id "uid" to the extent the user count never goes down. What's wrong with the parse objects's id as an id?).
Most of the parse functions return promises, and using them is the only way to not go nuts trying to nest callbacks. So...
Parse.Cloud.define("test", function(request, response) {
Parse.Cloud.useMasterKey();
var uid;
var query = new Parse.Query(Parse.User);
query.count().then(function(count) {
uid = count;
return query.get(request.params.objectId);
}).then(function(object) {
object.set("username", request.params.name);
object.set("email", request.params.email);
object.set("uid", uid);
var acl = new Parse.ACL();
acl.setPublicWriteAccess(false);
acl.setPublicReadAccess(false);
object.setACL(acl);
return object.save();
}).then(function (object) {
response.success(object);
},function(error) {
response.error("Error Message");
});
});
I am facing an issue in parse cloud code. The following is updating score and change date in my gamescore table. But it is not working. while I am doing same in my web code and it is working fine. Am I doing anything wrong here ?
'use strict';
var GameScore = Parse.Object.extend('GameScore');
Parse.Cloud.define('editScore', function(req, res) {
var query = new Parse.Query(GameScore);
query.get(req.params.objectId, {
success: function(gameScore) {
gameScore.set('score', req.params.score);
gameScore.set('date', req.params.date);
gameScore.save(null);
gameScore.fetch(myCallback);
},
error: function(err) {
return res.error(err);
}
});
});
If so then please help me so that I can make it working.
Try adding Parse.Cloud.useMasterKey(); inside the function to bypass any ACL restrictions that could be causing an issue. Example:
var GameScore = Parse.Object.extend('GameScore');
Parse.Cloud.define('editScore', function(req, res) {
// use Master Key to bypass ACL
Parse.Cloud.useMasterKey();
var query = new Parse.Query(GameScore);
query.get(req.params.objectId, {
success: function(gameScore) {
gameScore.set('score', req.params.score);
gameScore.set('date', req.params.date);
gameScore.save(null);
gameScore.fetch(myCallback);
},
error: function(err) {
return res.error(err);
}
});
});
You have 3 issues:
you're not waiting for the save to finish
you're not calling res.success()
you're referencing myCallback which from what you've shown us isn't defined
Simple solution is to replace this line:
gameScore.save(null);
With this code:
gameScore.save().then(function () {
res.success();
});
If you really do need that fetch call you would chain that in:
gameScore.save().then(function () {
return gameScore.fetch(myCallback);
}).then(function () {
res.success();
});
var GameScore = Parse.Object.extend('GameScore');
Parse.Cloud.define('editScore', function(req, res) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query(GameScore);
query.get(req.params.objectId, {
success: function(gameScore) {
gameScore.set('score', req.params.score);
gameScore.set('date', req.params.date);
gameScore.save().then(function() {
gameScore.fetch(callback);
});
},
error: function(err) {
return res.error(err);
}
});
});
using master key we are overriding acl. using then promise method we are calling callback functions after otherwise there is a possibility to get the old data.
I have an Angular service that takes in a roleId and userId and assigns the user to that role and make a pointer in User to that role.
app.service('CRUD', function () {
this.addUserToRole = function (roleId, userId) {
// first we have to find the role we're adding to
var query = new Parse.Query(Parse.Role);
return query.get(roleId, {
success: function (role) {
// then add the user to it
var Database = Parse.Object.extend("User");
var query = new Parse.Query(Database);
console.log(role);
return query.get(userId, {
success: function (user) {
console.log(user);
role.getUsers().add(user);
role.save();
// now we need to tell the user that he has this role
console.log(user);
user.attributes.role.add(role);
user.save();
return user;
},
error: function (err) {
return err;
}
});
},
error: function (err) {
console.log(err);
}
});
}
});
I'm getting {"code":206,"error":"Parse::UserCannotBeAlteredWithoutSessionError"} on user.save();
After some research, I arrived at this website. He uses this code snippet as a JS SDK example:
Parse.Cloud.run('modifyUser', { username: 'userA' }, {
success: function(status) {
// the user was updated successfully
},
error: function(error) {
// error
}
});
and mentions something about a useMasterKey() function.
I'm still unsure how to fix this error.
Add
Parse.Cloud.useMasterKey();
at the beginning of your function.
Set it up as a background job. That is the code snip you found I think and a simpler far more secure means of fondling users and roles
https://parse.com/docs/cloud_code_guide#jobs