Parse Javascript - Adding user error - javascript

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.

Related

UserCannotBeAlteredWithoutSessionError when updating PFUser on Parse from Heroku node.js app

I'm trying to update a PFUser in my Parse database from a node.js app running on Heroku. I'm calling the Parse cloud function from an iOS app.
Here's the part of the code I use to update the user on parse as well as creating the user on Stripe (the Stripe part works fine):
Parse.Cloud.define("createCustomerWithCreditCardToken", function(request, response) {
var userId = request.user.id;
var sourceId = request.params.creditCardToken;
var customerId;
var userSessionToken = request.user.getSessionToken();
console.log('userId: ' + userId + ' source: ' + sourceId + ' userSessionToken: ' + userSessionToken);
stripe.customers.create({
source: sourceId,
description: userId
}, function(error, customer) {
if (error !== null) {
response.error('error creating customer: ' + error);
}else {
var userQuery = new Parse.Query('User');
userQuery.equalTo('objectId', userId);
userQuery.first({sessionToken: userSessionToken}).then(function(user) {
console.log('user from parse query: ' + user.get("username"));
user.set("stripeCustomerId", customer.id);
user.save(null, {
success: function(parseCustomer) {
console.log('customer saved to parse: ' + parseCustomer);
},
error: function(error, parseCustomer) {
console.log('customer save failed: ' + JSON.stringify(error, null, 2) + ' with error: ' + JSON.stringify(parseCustomer,null, 2));
}
});
});
customerId = customer.id;
console.log('customerId: '+ customerId);
// response.success(customer);
response.success('Customer: ' + JSON.stringify(customer, null, 2) + 'error: ' + error);
}
});
});
I get the following error log output when I run this:
error log output
error: { "code": 206, "message": "Parse::UserCannotBeAlteredWithoutSessionError" }
In this post the current user concept in a node.js app context is discussed by a Parse engineer.
Also in Cloud Code, the concept of a method that returns the current
user makes sense, as it does in JavaScript on a web page, because
there’s only one active request and only one user. However in a
context like node.js, there can’t be a global current user, which
requires explicit passing of the session token.
Essentially he advises to do this:
Parse.Cloud.define('findBacon', function(req, res) {
var token = req.user.getSessionToken();
var query = new Parse.Query('Bacon');
// Pass the session token to the query
query.find({ sessionToken: token }).then( ... );
});
I have also tried using {useMasterKey:true} instead of {sessionToken:userSessionToken} which produces the same error.
I might just be missing some obvious detail, but I just can't seem to find it. Any ideas on how to solve this are greatly appreciated.
Turns out there's a third way of handling credentials:
Parse.Cloud.useMasterKey();
I placed this line in the beginning of the entire method, that did it for me. I'm not sure of the implications of giving the whole function these credentials though.
I'm not sure when you would use the other options either.
If someone comes across this and would like to elaborate, I'll be happy to give the right answer to a good explanation of when to grant which credentials.

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

Unable to access vline.Message object with postMessage()

While implementing the vLine API, I came up with a problem. When using the postMessage() method of the vline.Channel class, the message was successfully received by the target user, but the the success callback of vline.Promise object did not return a valid vline.Message object. At least I don't have acess to some of the vline.Message methods, like getChannel() or getCreationTime().
Code:
$channel.postMessage(textMessage)
.done(function (message) {
console.log("Message sending successfull || Message sent to " + message.getChannel().getDisplayName() + " at " + message.getCreationTime());
},
this)
.fail(function (err) {
console.log("Message sending failed || Error Type: " + err.type + " || Error Message: " + err.message);
},
this);
Result (console log):
Message sending failed || Error Type: undefined || Error Message: Object #<Object> has no method 'getChannel'
Is this result of a API change that has not been yet referenced on the vLine Developer site or is there an error on the code?
This was a bug on our end; sorry about that. It should now be fixed.

Parse Cloud Code: Can you pass objects in a push notification?

I'm creating a push notification similar to this sample code provided by Parse:
Parse.Cloud.afterSave('Activity', function(request) {
if (request.object.get("type") === ("comment") {
var message = request.user.get('displayName') + ': ';
message += request.object.get('content').trim();
var query = new Parse.Query(Parse.Installation);
query.equalTo('user', request.object.get("toUser"));
Parse.Push.send({
where:query,
data: {
alert: message,
badge: 'Increment'
}
});
}
});
My question is: in the data area of the Parse.Push.send, can I send an entire message object, where Message is a custom class I created? If so, what would that look like?
If you already have the class created and saved an object why not just send the object ID and query it asynchronously once the user goes to retrieve the push notification?
The message object does not need to waste up space and be sent via push just a pointer is required.
I'm in the process of implementing something similar and this is the route I plan to use.
You can serialize the object in JSON/XML format and then deserialize it when you receive the push notification.
You can't send objects directly. You'll get an exception (I had this issue a few days ago but didn't write the name of the exception down). The best answer is so far is by BrentonGray88.
I'm assuming you're not using Android because you included the badge: "Increment" value, but this is how I would do it:
Android code to send the notification:
Make sure the Comment object has a pointer (_User) column to the User who sent the comment. When you create the comment, include user.put("commentAuthor", ParseUser.getCurrentUser()); in your Android code so that you can always access the user who created the comment.
Now you need to query the Comment to send its objectId through to the push notification.
ParseQuery<ParseObject> query = new ParseQuery<>("Comment");
query.whereEqualTo("objectId", I AM NOT SURE WHAT CONDITION YOU WANT HERE);
query.findInBackground((comment, e) -> {
if (e == null) for (ParseObject commentObject: comment) {
String recipientObjectId = commentObject.getParseObject("commentAuthor").getObjectId();
final Map<String, Object> params = new HashMap<>();
// This is to send the notification to the author of the Comment
params.put("recipientObjectId", recipientObjectId);
// This is so we can use values from the Comment in the notification
params.put("commentObjectId", commentObject.getObjectId());
// This is a required lined
params.put("useMasterKey", true);
ParseCloud.callFunctionInBackground("pushMessage", params, new FunctionCallback<String>() {
public void done(String result, ParseException e) {
if (e == null) {
Log.d(getClass().toString(), "ANNOUNCEMENT SUCCESS");
} else {
System.out.println(e);
Log.d(getClass().toString(), "ANNOUNCEMENT FAILURE");
}
}
});
}
});
Now for the query in your Cloude Code:
Parse.Cloud.define("pushMessage", function (request, response) {
// Again, we are sending the notification to the author of the Comment
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo('user', request.params.get("recipientObjectId"));
// We retrieve information from the Comment created by that author
var commentQuery = new Parse.Query(Parse.Comment);
commentQuery.equalTo('objectId', request.params.commentObjectId);
commentQuery.get("commentObjectId", {
success: function(userObject) {
var displayName = userObject.get("displayName");
var content = userObject.get("content");
var message = displayName + ': ';
message += content.trim();
Parse.Push.send({
where: pushQuery,
data: {
alert: message
},
}, {
useMasterKey: true,
success: function () {
response.success("Success!");
},
error: function (error) {
response.error("Error! " + error.message);
}
});
console.log();
},
error: function(error) {
console.log("An error occured :(");
}
});
});
Sorry I'm not the best at JavaScript but that's kind of how I'd do it. Best of luck! :)

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.

Categories

Resources