How to get rows count in Cloud Code in Parse - javascript

I have tried this code: I keep getting success/error was not called.
Parse.Cloud.beforeSave("Offer", function(request, response) {
var duplicationQuery = new Parse.Query("Offer");
console.log(duplicationQuery.count);
});
Then I tried this:
Parse.Cloud.beforeSave("Offer", function(request, response) {
var duplicationQuery = new Parse.Query("Offer");
duplicationQuery.count()
{
success: function(httpResponse) {
console.log(httpResponse.text);
response.success(httpResponse.text);
console.log("Row count: "+duplicationQuery.count);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error('Request failed with response code ' + httpResponse.status);
}
}
});
I guess I'm stuck with improper syntax. Can someone help me out?

I would say stay away from count queries as they are inefficient. Simply do a find query and get the count using the length property of your results.
var duplicationQuery = new Parse.Query("Offer");
duplicationQuery.limit(1000); // max limit
duplicationQuery.find().then( function(results) {
console.log(results.length);
});
Also bear in mind that the max number of records you can get in any query is limited to 1000.

Related

Parse cloud code - query user issue in "normal" function

I cannot get cloud code to query a user when using a "standard" function...
If I define the function (as below), it works fine...
Parse.Cloud.define("findUser1", function(request, response){
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.equalTo("objectId", "2FSYI1hoJ8"); // "2FSYI1hoJ8" is the objectId of the User I am looking for
query.first({
success: function(user){
response.success(user);
},
error: function(error) {
console.error(error);
response.error("An error occured while lookup the users objectid");
}
});
});
In this version, the function will be called, but the query within will not...
function findThisUser(theObject){
console.log("findThisUser has fired... " + theObject); //confirms "theObject" has been passed in
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.equalTo("objectId", "2FSYI1hoJ8"); // "2FSYI1hoJ8" is the value of "theObject", just hard coded for testing
query.first({
success: function(users){
console.log("the user is... " + users);
// do needed functionality here
},
error: function(error) {
console.error(error);
}
});
};
Cloud code does not allow global variables, and I do not see how to pass in a variable to a "defined" function from another one. This is crucial as an outside function must be called to run the required tasks on the returned user. (This happens elsewhere and has to happen AFTER everything else does. This is the confirmation, and is supposed to be used by other functions as well) All potential information found to date has not helped, and the only experience I have in server side javascript is what I have cobbled together from other cloud code...
Any ideas on what I am missing?
This link may help, i had similar issue yesterday and after moving the code a little, and having the response.success(user); in my function all worked fine.
Parse Cloud Code retrieving a user with objectId
Not your exact issue - but this may help.
Heres is the code i use now:
Parse.Cloud.define("getUserById", function (request, response) {
//Example where an objectId is passed to a cloud function.
var id = request.params.objectId;
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.equalTo("ObjectId", id);
query.first(
{
success: function(res) {
response.success(res);
},
error: function(err) {
response.error(err);
}
});
});

Parse Cloudcode query error 141

If I run the Parse JavaScript code below locally, the query works fine. However, when I adapt the code to run as Parse cloudcode, the same query is not executed, and when I test the query content I get an error with code 141.
I have tested both functions at various points. The parameter comp_id and request.params.comp_id are the same.
Parse JavaScript query (run locally, works fine)
function testOne(comp_id) {
Parse.initialize(*****,*****);
var Competition = Parse.Object.extend("Competition");
var query = new Parse.Query(Competition);
console.log(query); // <~ gets a valid query
query.get(comp_id, {
success: function(competition) {
console.log(competition.id);
},
error: function(competition, error) {console.log(error);}
});
}
Parse cloudcode query (query does not execute, error 141)
Parse.Cloud.define("testOneCloud", function(request, response) {
var comp_id = request.params.comp_id;
var Competition = Parse.Object.extend("Competition");
var query = new Parse.Query(Competition);
msg = query; // <~ gets undefined error 141
query.get(comp_id, {
success: function(competition) {
msg = competition.id; // <~query success code does not get executed
},
error: function(competition, error) {console.log(error);}
});
response.success(msg);
});
Any idea why one of these two seemingly identical Parse programs work and the other doesn't?
It seems the undeclared msg variable is causing the problem. How about (eliminating the extra variable and using promises):
Parse.Cloud.define("testOneCloud", function(request, response) {
var Competition = Parse.Object.extend("Competition");
var query = new Parse.Query(Competition);
query.get(request.params.comp_id).then(function(competition) {
response.success(competition.id);
}, function(error) {
response.error(error);
});
});

Why Parse.Query function is not work?

I use to Parse Cloud Code.
now I can not unsolvable problem.
It is this code.
This 1 code is not problem working ,but 2 code is not work.
Why?
var className = Parse.Object.extend("Post");
//--------------------------1 Start-----------------------------
var post = new className();
post.set("ArtistName","Name");
post.set("Collection","アルバム");
post.set("MusicTitle","タイトル");
post.set("user",toUser);
post.save(null, {
success: function(gameScore) {
console.log("クラス保存成功");
}
});
//---------------------------1 end----------------------------
//-------------------------2 start-----------------------------
var query = new Parse.Query(className);
//query.equalTo("user", toUser);
query.count({
success: function(count) {
console.log("Sean has played " + count + " games");
},
error: function(error) {
console.log("エラー");
}
});
//--------------------------2 end-------------------------------
From the code you provide is valid except one line. You have to call response success as below;
var query = new Parse.Query(className);
//query.equalTo("user", toUser);
query.count({
success: function(count) {
console.log("Sean has played " + count + " games");
response.success(count);
},
error: function(error) {
console.log("Error");
response.error(error);
}
});
After calling the success you can see the count both in the logs and function caller.
Hope this helps.
Regards.

order of operations parse cloud

I was wondering what the order of operations are in the parse cloud. I currently am running into trouble trying to do multiple things at once inside my job on the cloud. I am currently trying to make an HTTP request for each user in my user table (there are 2) and then get the webpage or httprequest.text from the webpage. My code is as followed
Parse.Cloud.job("WeatherUpdates2", function(request, status) {
var query = new Parse.Query(Parse.User);
query.exists("City");
query.each(
function(result){
var object = result;
console.log(object.id);
var city = object.get("City");
city = city.replace(" ", "");
city = city.replace(" ", "");
// get the country code.
var countryCode = object.get("CountryCode");
var woeidUrl = "http://where.yahooapis.com/v1/places.q(" + city + "," + countryCode + ")?appid=(appid)";
console.log(woeidUrl);
var woeID = "An error occured retrieving your WOEID.";
Parse.Cloud.run('httpRequest', { url: woeidUrl }, {
success: function(WOEID) {
console.log("returned from http request.");
},
error: function(error) {
console.log("Error occurred while making request for WOEID " + error.message);
status.error(error.message);
}
});
},
{
success: function() {
// results is an array of Parse.Object.
console.log('#Query');
status.success("Updated Records!!");
},
error: function(error) {
// error is an instance of Parse.Error.
console.log('#error');
response.error("Failed to save vote. Error=" + error.message);
}
});
});
Where the job httpRequest is:
Parse.Cloud.define("httpRequest", function(request, response) {
var webpage = "Something went wrong.";
Parse.Cloud.httpRequest({
url: request.params.url,
success: function (httpResponse) {
webpage = httpResponse.text;
webpage = webpage.toString();
response.success(webpage);
},
error: function (error)
{
console.log("Error in http request " + error.message);
response.error(error.message);
}
});
});
now I would expect to be printed would be the, object id of first user, their url, the job running, the message"returned from http request." then repeated another time for the second user and finally the job finishing with the message "Updated Records". but instead I get:
I2014-07-22T15:15:16.013Z] A5hod7qKE3
I2014-07-22T15:15:16.045Z] http:/where.yahooapis.com/v1/places.q(Draper,US)?appid=(appid)
I2014-07-22T15:15:16.053Z] GmuqxpTUpM
I2014-07-22T15:15:16.066Z] http:/where.yahooapis.com/v1/places.q(SaltLakeCity,US)?appid=(appid)
I2014-07-22T15:15:16.082Z] #Query
I2014-07-22T15:15:16.131Z] v385: Ran cloud function httpRequest with:
Input: {"url":"http://where.yahooapis.com/v1/places.q(SaltLakeCity,US)?appid=(appid)"}
Result:
2487610TownSalt Lake CityUnited StatesUtahSalt LakeSalt Lake City40.777561-111.93071740.699890-112.10125740.852951-111.739479511America/Denver
I2014-07-22T15:15:16.141Z] v385: Ran cloud function httpRequest with:
Input: {"url":"'http://where.yahooapis.com/v1/places.q(Draper,US)?appid=(appid)'"}
Result:
http://where.yahooapis.com/v1/schema.rng'" xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:start="0" yahoo:count="1" yahoo:total="11">2393601TownDraperUnited StatesUtahDraper8402040.524139-111.86627240.442921-111.92212740.544361-111.78304349America/Denver
I removed 1 / from both the printing urls so I could posts this because I don't have high enough rep to post more than 2 links. I also have put in my appid into the (appid) so the url does return to me the according woeid from yahoo.com. The problem here being I can't actually get into the success function of the http request job. Any help is greatly appreciated!
EDIT:
I was trying to figure out how to run a job in a for loop but couldn't get it to work. I tried to make a promise and do what Fosco said below, but have had no luck. Here is my code.
for(var i = 0; i < woeIDs.length; i++)
{
console.log("hello");
var weatherURL = "http://weather.yahooapis.com/forecastrss?w=" + woeIDs[i] + "&u=f";
var promise = Parse.Cloud.run('httpRequest', { url: weatherURL }, {
success: function(WOEID) {
console.log("got here");
},
error: function(error) {
console.log("Error occurred while making request for WOEID " + error.message);
status.error(error.message);
}
});
Parse.Promise.when([promise]).then(function() { status.success(); });
}
if I run this code I get a hello twice then the two job calls then the "got here" message once. I have tried adding a return statement to it and with no luck also. Thanks again for all the help!!!
The issue here is that inside the each callback, you need to return the promise from your cloud function call if you want to ensure the tasks complete, and have it wait before going to the next object.
Simplified and using promises:
query.each(function(object) {
...
return Parse.Cloud.run(...);
}).then(function() {
// success
}, function(err) {
// error
});
For looping over a promise-returning function like Parse.Cloud.run:
var promises = [];
for (i = 0; i < 5; i++) {
promises.push(Parse.Cloud.run('...', {}));
}
Parse.Promise.when(promises).then(function() {
// all done
}, function(err) {
// error
});

ParseApp Saving data from httpRequest

I am writing a simple app where I need to get the data from a http get api call and store it in Parse for some reason not all the data is stored. Also the http call returns before saving all the data here is the code.
How can I make it to return only after saving all the data?
Parse.Cloud.httpRequest({
url: 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=apikey',
success: function(httpResponse) {
var jsonobj = JSON.parse(httpResponse.text);
var total = jsonobj.movies.length;
for ( var idx in jsonobj.movies) {
var movie = new Movie();
movie.save(new Movie(jsonobj.movies[idx])).then(
function(object){
console.log(object)
},
function(error){
console.log(error);
}
)
}
response.send("All saved");
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.send("Failed");
}
})
You need to aggregate all the promises you used via an aggregation function, in the case of parse promises, it's .when :
Parse.Cloud.httpRequest({
url: 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=apikey',
success: function(httpResponse) {
var jsonobj = JSON.parse(httpResponse.text);
var total = jsonobj.movies.length;
var results = [];
// do NOT iterate arrays with `for... in loops`
for(var i = 0; i < jsonobj.movies.length; i++){
var movie = new Movie();
results.push(movie.save(new Movie(jsonobj.movies[i]))); // add to aggregate
}
// .when waits for all promises
Parse.Promise.when(promises).then(function(data){
response.send("All saved");
});
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.send("Failed");
}
})
Although, it might be better to use promises for the httpRequest too, this should work.

Categories

Resources