Parse Cloud Code query after save don't works - javascript

After saving an array of objects, I do a query for count the number of elements of a class, but the code doesn't run.
Parse.Cloud.define("saveItem", function(request, response) {
Parse.Cloud.useMasterKey();
... (Updating objects...)
Parse.Object.saveAll([item, activity], {
success: function(list) {
response.success("saved"); // <--- THE OBJECTS ARE SAVED, ALLRIGHT
var query = new Parse.Query("Item"); // <--- FROM HERE
query.count({
success: function(count) {
console.log("inside count"); // <--- NOT ENTER HERE!!
},
error: function(error) {
// The request failed
}
});
},
error: function(error) {
response.error(error);
},
});

You need to complete your operations before calling response.success("saved")
Calling response.success is effectively killing the rest of your code.
Parse.Cloud.define("saveItem", function(request, response) {
Parse.Cloud.useMasterKey();
//... (Updating objects...)
Parse.Object.saveAll([item, activity], {
success: function (list) {
var query = new Parse.Query("Item");
query.count({
success: function (count) {
response.success(count);
},
error: function (error) {
// The request failed
response.error("Unable to count items...");
}
});
},
error: function (error) {
response.error(error);
},
});
});

Related

Calling sync ready made async ajax javascript function

I want to call this function on button click after login and wait for result, to get token value. This function cannot be changed, it is async and supplied from other currently unavailable team.
I already tried something like this, but with no success. I get web service results, but I can't write appropriate sync call to wait to return token.
function getToken() {
param1 = "123456";
ajax_oauth(param1, function (success, response) {
success: return response.token;
});
}
function ajax_oauth(param1, callback) {
APP.debug("oauth login with param1 " + param1);
try {
APP.blockUI();
var DeviceID = APP.readRegistry(APP_CONFIG.REGISTRY.DeviceID);
//---------------------------------------------------------------
$.ajax(
auth_token_url,
{
method: "GET",
accept: 'application/json',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({
'param1': param1,
'deviceId': DeviceID
}),
xhrFields: {
withCredentials: false
},
statusCode: {
201: function (response) {
APP_STATE.hasOauth = true;
APP.debug('got response 200 from oauth');
auth.login(response.token); //TODO read expiration from token
try {
var decoded = jwt_decode(response.token);
APP_STATE.uid = decoded.uid;
} catch (err) {
APP.error("unable to decode token " + JSON.stringify(err));
}
},
401: function () {
},
500: function () {
},
503: function () {
}
},
success: function (response) {
APP.unblockUI();
APP_STATE.restAvailable = true;
},
error: function (jqXHR, textStatus, errorThrown) {
APP.unblockUI();
APP_STATE.restAvailable = false;
APP.restError(auth_token_url, jqXHR, errorThrown, textStatus);
APP.callback(callback, false);
}
}
);
} catch (err) {
APP.error("unable to do oauth login, " + err);
}
};
After user clicks on login button, I want to call function ajax_oauth and to return token if params ok. If not, to return login error. Login can't be async, as far as I can see.
For whatever reason you can't tap into the original ajax response, you could intercept the request using $.ajaxPrefilter.
From your code it looks like auth_token_url has a global reference. You could use this to intercept the call by matching the outgoing request on the resource URL.
$.ajaxPrefilter('json', function(options, originalOptions, jqXHR) {
if (options.url === auth_token_url) {
jqXHR.done(function(response) {
try {
var decoded = jwt_decode(response.token);
console.log(decoded);
} catch (err) {
APP.error("unable to decode token " + JSON.stringify(err));
}
});
}
});
Note that this needs to be declared well before the request is made preferably after jQuery is loaded.

Parse Connection Times out only for one specific function

Below is my cloud code in which I am attempting to use to create a Friend Database, Both the first and the third function work fine however the AcceptFriendRequest function times out as if there is no server there with the error code 100. I am very lost as this happens 100% of the time. All help is appreciated.
Parse.Cloud.define("AddFriendRequest", function (request, response) {
var FriendRequest = Parse.Object.extend("FriendsIncoming");
var FRequest = new FriendRequest();
var user = request.user;
var query = new Parse.Query(Parse.User);
query.equalTo("username", request.params.username);
query.find({
success: function (people) {
if(people.length == 0)
{
response.success(-5);
return;
}
var person = people[0];
FRequest.set("OwnerID", user.id);
FRequest.set("TargetFriend", person.id);
FRequest.set("Status", 0);
var query = new Parse.Query("FriendsIncoming");
query.equalTo("OwnerID", user.id);
query.equalTo("TargetFriendID", person.id);
query.find({
success: function (results) {
if (results.length > 0) {
response.success(1);
return;
}
FRequest.save(null, {
success: function (Friend) {
response.success(2);
},
error: function (Friend, error) {
response.error(3);
}
});
response.error(-2);
},
error: function () {
response.error(-1);
}
});
}
,
error: function (Friend, error) {
response.error(-4);
}
});
});
Parse.Cloud.define("AcceptFriendRequest", function (request, response) {
var user = request.user;
var query = new Parse.Query("FriendsIncoming");
query.equalTo("OwnerID", user.id);
query.equalTo("TargetFriendID", request.params.TargetFriendID);
query.find({
success: function (results) {
if (results.length > 0) {
response.success(1);
return;
}
FRequest.save(null, {
success: function (Friend) {
response.success(2);
},
error: function (Friend, error) {
response.error(3);
}
});
response.error(-2);
},
error: function () {
response.error(-1);
}
});
});
Parse.Cloud.define("RetrieveFriends", function (request, response) {
var query = new Parse.Query("FriendsAccepted");
var results = [];
query.find().then(function (Friends) {
for (var i = 0; i < Friends.length; i++) {
results.push(Friends[i]);
}
// success has been moved inside the callback for query.find()
response.success(results);
}, function (error) {
// Make sure to catch any errors, otherwise you may see a "success/error not called" error in Cloud Code.
response.error("Could not retrieve Posts, error " + error.code + ": " + error.message);
});
});
It seems like the FRequest in the AcceptFriendRequest is not initialized...
add this in the inside of the function. The timeout on parse.com is 15 seconds for cloud function and for afterSave 3 secs. They might changed it though cause they are shutting down
var FriendRequest = Parse.Object.extend("FriendsIncoming");
var FRequest = new FriendRequest();

Relation field query not working as expected

I have an Event table and it has a column called "attendees" which is a Relation type to _User [many to many].
I have tried the following to get a list of all _Users who are attending an Event based on the objectId for the event. In my code below the success and error callbacks are not being called. (Neither SUCCESS or ERROR is being printed to the error log.)
Parse.Cloud.define("cancelEvent", function(request, response) {
var query = new Parse.Query("Event");
query.get(request.params.eventId, {
success: function(event) {
// event.set("status", "cancelled");
// event.save();
// notify attendees of cancellation
var relation = event.relation("attendees");
var innerQuery = relation.query();
innerQuery.find({
success: function(attendees) {
console.error("SUCCESS");
},
error: function(error) {
console.error("ERROR");
}
});
event.save();
response.success();
},
error: function(object, error) {
console.error("Failed to cancel event.");
response.error(error);
}
});
});
Move event.save();
response.success();
to inside the success callback like this
Parse.Cloud.define("cancelEvent", function(request, response) {
var query = new Parse.Query("Event");
query.get(request.params.eventId, {
success: function(event) {
// event.set("status", "cancelled");
// event.save();
// notify attendees of cancellation
var relation = event.relation("attendees");
var innerQuery = relation.query();
innerQuery.find({
success: function(attendees) {
console.error("SUCCESS");
event.save();
response.success();
},
error: function(error) {
console.error("ERROR");
}
});
},
error: function(object, error) {
console.error("Failed to cancel event.");
response.error(error);
}
});
});

Parse Cloud Code beforeSave not running on update

I have defined a Parse Cloud Code function for beforeSave below.
Parse.Cloud.beforeSave(Parse.User, function(request, response) {
Parse.Cloud.useMasterKey();
var publicACL = new Parse.ACL();
publicACL.setPublicReadAccess(true);
publicACL.setPublicWriteAccess(true);
request.object.setACL(publicACL);
response.success();
});
This code runs correctly whenever I save a new Parse.User. However, when I try to update a pre-existing Parse.User, the code does not execute. Any thoughts? Below is the code I am using to update my user.
function updateStudentTypes(id, studentType, chkBox) {
var query = new Parse.Query(Parse.User);
query.get(id, {
success: function(user) {
var typeList = user.get("studentType");
if(!chkBox.checked)
typeList = removeStudentType(typeList, studentType);
else
typeList = addStudentType(typeList, studentType);
user.set("studentType", typeList);
user.save(null, {
success: function(user) {
//alert('New object created with objectId: ' + user.id);
},
error: function(user, error) {
alert('Failed to update user: ' + error.message);
}
});
},
error: function(object, error) {
alert("Error querying user: " + error);
}
});
}
Add this to the beginning of your updateStudent method:
Parse.Cloud.useMasterKey();
Edit: I thought your code was cloud code, not client side javascript.

Parse, Function only works for the current user

The following function seems to only work for my Current user, any other ObjectId that I type into the input will return a Post (Bad Request) error in the console.
var query = new Parse.Query(Parse.User);
var userInput = $('#inputObject').val();
query.equalTo("objectId", userInput);
query.first({
success: function(result) {
console.log(result.id);
result.set('money', 20);
result.save();
},
error: function(error) {
console.log("None found.");
}
});
The problem with this is that the Parse user object is only modifiable by the current user. You can get around this by creating a Cloud Code function, which modifies the money value for the intended user. Note, the cloud code function must call Parse.Cloud.useMasterKey(); Source
CloudCode Function:
Parse.Cloud.define("setMoney", function(request, response) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.equalTo("objectId", request.params.userId);
query.first({
success: function (result) {
console.log(result.id);
result.set('money', 20);
result.save();
response.success();
},
error: function (error) {
console.log("None found.");
response.error(error);
}
});
});
JavaScript Call
Parse.Cloud.run("setMoney", {userId: userInput}, {
success: function(result) {
// Success
},
error: function(error) {
// Error
}
});

Categories

Resources