order of operations parse cloud - javascript

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
});

Related

Parse.Cloud.run not recognizing variables

I am trying to link my website to a Parse server using mongodb. It was running well, and saving so i could see in parse dashboard, and mlab. I attempted to add a new variable which resulted in me messing something up. When this get run it throws an error saying address is not defined on the line with Parse.Cloud.run.
document.getElementById("btn").addEventListener("click", function(){
var name = document.getElementById('inp1').value;
var address = document.getElementById('inp2').value;
var city = document.getElementById('inp3').value;
var state = document.getElementById('inp4').value;
var zipcode = document.getElementById('inp5').value;
var Apartment = Parse.Object.extend("Apartment");
var apartment = new Apartment();
apartment.set("name", name);
apartment.set("address", address);
apartment.set("city", city);
apartment.set("state",state);
apartment.set("zipcode", zipcode);
apartment.save(null, {
success: function(apartment) {
// Execute any logic that should take place after the
object is saved.
alert('New object created with objectId: ' + prod.id);
},
error: function(error) {
// Execute any logic that should take place if the save
fails.
// error is a Parse.Error with an error code and
description.
alert('Failed to create new object, with error code: ' +
error.description);
}
});
});
Parse.Cloud.run("registerApartment",{"name":name,"address":address,"city":
city, "state": state,"zipcode":zipcode,"map":map}, {
success: function(savedApartment){
console.log(savedApartment);
}, error: function(error){
console.log(error);
}
})
thank you ahead of time!
cloud code
Parse.initialize('#');
Parse.serverURL = 'http://localhost:1337/parse';
Parse.Cloud.define("registerApartment", function(req,res){
var params = request.params;
var name = params.name;
var address = params.address;
var city = params.city;
var state = params.state;
var zipcode = params.zipcode;
var Apartment = Parse.Object.extend("Apartment");
var apartment = new Apartment();
apartment.set("name", name);
apartment.set("address", address);
apartment.set("city", city);
apartment.set("state",state);
apartment.set("zipcode", zipcode);
apartment.set("map", map);
console.log(apartment);
apartment.save(null, {
success: function(savedApartment){
console.log("Succesfully saved bitch");
response.success(savedApartment);
}, error: function(error){
console.log(error);
response.error(error);
}
})
});
could you double check your server where you define the cloud code?
Your code should be something along this line:
Parse.Cloud.define("registerApartment", function(req,res){
---your codes---
});
Make sure that your Parse.Cloud.run() is calling what you defined back at your server.
Edit:
Try to use this code instead of your current one:
Parse.Cloud.run("registerApartment",{name:name,address:address,city:
city, state: state,zipcode:zipcode,map:map}, {
success: function(savedApartment){
console.log(savedApartment);
}, error: function(error){
console.log(error);
}
})
All i did was remove the quotes when parsing in a parameter. This should work fine :)

How to get rows count in Cloud Code in Parse

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.

Parse.com JavaScript query error handling does not work

I'm playing around with the Parse backend and NodeJS but I have a problem right now and I am not able to figure it out. I have a get request like this.
app.get("/movie", function (req, res) {
var Review = Parse.Object.extend("Review");
var query = new Parse.Query(Review);
var movie = req.query.movie;
query.equalTo("movie", movie);
query.first({
success: function (movie) {
console.log("Success");
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});});
This works fine but the error handling kinda doesn't. If, for example, I change
query.equalTo("movie", movie);
to query.equalTo("movie", "xyz");
or query.equalTo("abc", "xyz");
which does not exist in my table, I'm still getting the success statement. And yes, I have restarted the server every time.
Update
I tried the same query using the iOS SDK(Swift) and here I get into the error case. I always get the same error though, which shouldn't be, but at least I get an error while in the JS sample I always get into the success case.
I believe query.first() will not error if it does not find a "first" object. You can check for (movie == null) on the success return.
Update:
Try writing it this way:
app.get("/movie", function (req, res) {
var movie = req.query.movie;
var query = new Parse.Query("Review");
query.equalTo("movie", movie);
query.first().then(function (movie) {
// Success
console.log("Success");
}, function (error) {
// Error
console.log("Error: " + error.code + " " + error.message);
});
});
query.find() always success even if there is no match data in your table/collections
Let's try it
query.find().then(function (movies) {
if(movies.length > 0){
console.log("success");
}else{
console.log("query success but no data found");
}
}, function (error) {
// Error
console.log("Error: " + error.code + " " + error.message);
});

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.

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