Parse.com JavaScript query error handling does not work - javascript

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

Related

Parse Javascript - Adding user error

I created a factory in angularJS to store data to Parse User object. Every time I click to process the details and open an account for the user, it shows the following error in console:
Failed to load resource: https://api.parse.com/1/users the server
responded with a status of 400 (Bad Request)
I checked if the service parameter is valid with attributes content, and yes it has content (not empty). This is the service body:
.factory('CreateUserService', function() {
return {
createAccount: function(user) {
console.log("Service User: " + user.name);
var parseUser = new Parse.User();
parseUser.set("username", user.username);
parseUser.set("email", user.username);
parseUser.set("name", user.username);
parseUser.set("password", user.username);
parseUser.set("mobile", user.username);
/*Attempt to create user in DB*/
parseUser.signUp(null, {
success: function(parseUser) {
// Hooray! Let them use the app now.
//alert("success!");
return 1;
},
error: function(parseUser, error) {
// Show the error message somewhere and let the user try again.
//alert("Error: " + error.code + " " + error.message);
return error;
}
});
}
}
});
I added the Parse CDN in the index.html of my application with:
<script src="http://www.parsecdn.com/js/parse-1.6.7.min.js"></script>
Update: In Parse API Guide, this is the body of the signup:
user.signUp(null, {
success: function(user) {
// Hooray! Let them use the app now.
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
});
The user object in Parse (I review through the browser) is not showing any changes to the rows number hence user not added. Any idea what is going wrong?
Thanks
Update: When I deleted the existing empty user object in Parse and ran the code, it worked and created a user Object with all columns specified in the code. Then if I try to add another user, I get a POST error. There must be a way around this since signup method by parse surely considered adding multiple users to the User object.

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

jQuery.get read values from data

I cannot seem to access the values in the returned data array from a jQuery.getJSON and I cannot understand why. I have this same code working elsewhere in my app, biggest difference being this particular instance returns one row only, as opposed to multiple in the other places.
When I manually execute the script I can see this JSON output:
[{"total_energy":"34011.920000","earliest_install_date":"2012-01-01"}]
When I execute the code below, the data array is empty / undefined. If I change the ".getJSON" to ".get" I can now see the values in data but I still cannot access them. I have tried via data.total_energy but I get "undefined". Any help is appreciated.
The Javascript code:
jQuery.getJSON(url, function(data) {
console.log("Earliest Date= " + data.earliest_install_date);
console.log("Total Energy= " + data.total_energy);
})
.done(function() {
})
.fail(function(jqxhr, textStatus, error ) {
var sysError = textStatus + ", " + error;
showPopupMsg(errorClass, logoutFlag, "There was an error retrieving the Environmental Savings data.<br/>If the issue persists please contact SMA for support...<br/>Error: " + sysError);
})
.always(function() {
});
The result in the console is:
Earliest Date= undefined
Total Energy= undefined
Your JSON is an array:
[{"total_energy":"34011.920000","earliest_install_date":"2012-01-01"}]
You need to access the first element of the array returned like so:
jQuery.getJSON(url, function(data) {
console.log("Earliest Date= " + data[0].earliest_install_date);
console.log("Total Energy= " + data[0].total_energy);
})
.done(function() {
})
.fail(function(jqxhr, textStatus, error ) {
var sysError = textStatus + ", " + error;
showPopupMsg(errorClass, logoutFlag, "There was an error retrieving the Environmental Savings data.<br/>If the issue persists please contact SMA for support...<br/>Error: " + sysError);
})
.always(function() {
});
Try this:
jQuery.getJSON(url, {})
.done(function(data) {
console.log("Earliest Date= " + data.earliest_install_date);
console.log("Total Energy= " + data.total_energy);
})
.fail(function(jqxhr, textStatus, error ) {
var sysError = textStatus + ", " + error;
showPopupMsg(errorClass, logoutFlag, "There was an error retrieving the Environmental Savings data.If the issue persists please contact SMA for support...Error: " + sysError);
})
.always(function() {
});

Not passing proper parameters Parse.com

I am developing an application using Parse.com
According to it's error system, it's saying I'm not passing the proper parameters when trying to "login."
Here is my code:
function signInUser() {
Parse.initialize("", "");
var username = this.$("#signin-username").val();
var password = this.$("#signin-password").val();
Parse.User.logIn(username, password, {
success: function(user) {
alert("You successfully logged in!");
},
error: function(user, error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
I was board at work so I made up a simple register and login so you can compare with your code with mine.

How to get the context of a Web Sql error?

I start deploying an offline application on iPhones, but it's still under heavy developpment.
I have a simple error handler for my query :
db.transaction(tx) {
tx.executeSql("SELECT * FROM TABLE",[], successHandler, errorHandler);
});
function errorHandler(transaction, error) {
alert("Error : " + error.message);
}
When I test myself the application, and get an error, I manage to find what was the query generating the error. But when it's my users (distant users, of course), it's very difficult, as the error messages are not specific.
Is there a way to add context info to my error messages, for example the sql query, or a comment parameter ?
You could use a pattern like this:
db.transaction(tx) {
doQuery(tx, "SELECT * FROM TABLE",[],theSuccessHandler)
});
function doQuery(tx, query, values, successHandler) {
tx.executeSql(query, values, successHandler, errorHandler);
function errorHandler(transaction, error) {
alert("Error : " + error.message + " in " + query);
}
}
I ehanced Myrne answer to add query parameters and a free context string :
function doQuery(tx, query, values, successHandler, context)
{
tx.executeSql(query, values, successHandler, errorHandler);
function errorHandler(transaction, error)
{
var text_context = context != undefined && context != "" ? "(" + context + ") " : "";
alert("Error "+text_context+": " + error.message + " in " + query + " (params : "+values.join(", ")+")");
}
}
This will return this kind of error :
Error (function update_commande) : could not prepare statement (1 no such column: field3) in UPDATE table SET field2 = ?, field3 = ? WHERE field1 = ? (params : 1.63, 1449, 606)

Categories

Resources