afterSave member Parse Cloud Code not saving - javascript

I am attempting to save a username and userId after a user registers into a Runner Class within Parse. For some reason the information is not saving and I am not receiving an error. Can anyone give some advice?
Parse.Cloud.afterSave(Parse.User, function(request){
if(!request.object.existed()){
var RunnerClass = Parse.Object.extend("Runner");
var runner = new RunnerClass();
runner.set("username", request.object.get("username"));
runner.set("userId", request.object.id);
runner.save();
}
});

Your afterSave is incorrectly defined. There is no response for afterSave. Only on beforeSave.
Parse.Cloud.afterSave(Parse.User, function(request) {
...
}

You have to avoid using request.object.existed() in your afterSave trigger because it currently always returns false. This is unfortunately due to a known bug in Parse Cloud which is yet to be fixed. Instead you have to use the workaround given here in the bug report discussion: https://developers.facebook.com/bugs/1675561372679121/
The workaround is to replace request.object.existed() with the following boolean in your afterSave:
var objectExisted = (request.object.get("createdAt").getTime() != request.object.get("updatedAt").getTime());
Also make sure to use request.user instead of request.object in your code

Related

Trying to get a snapshot of a variable from firebase gives me an error

Problem
In a social media app I am making with react native and firebase, I am trying to grab the number of comments a post has using the snapshot function of a variable I have saved on my servers, then I am going to add one to this variable when a user adds a new comment. My code to do so is right here:
firebase.database().ref('posts').child(this.state.passKey).update({
comments: firebase.database().ref('posts/'+this.state.passKey).child('comments').snapshot.val() + 1
})
When I actually run this code, I get an error saying:
Reference.child failed: First argument was an invalid path = "undefined".
Paths must be non-empty strings and can't contain ".","#","$","[", or "["
At first I thought this might be that the "this.state.passKey" wasn't actually passing the key, but putting in a key I copied from the server didn't fix the problem.
My Server
-
To get the comments of particular post you should do like this
let postId='someId'
postRef=`/posts/${postId}`
firebase.database().ref(postRef).once("value", dataSnapshot => {
comment=dataSnapshot.val().comments
});
It looks like you're expecting this bit of code to query the database:
firebase.database().ref('posts/'+this.state.passKey).child('comments').snapshot.val() + 1
Unfortunately, it doesn't work that way. There's no snapshot property on a database Reference object returned by child() or ref().
Instead, you'll need to query the database at that reference, then when you're called back with its value, you can apply it elsewhere.
var ref = firebase.database().ref('posts/'+this.state.passKey+'/comments')
ref.once('value', function(snapshot) {
// use the snapshot here
})

Calling function in Ionic controller after data loaded

I am pulling data from firebase and depending on the data, I adjust show a different image. My data is taking time to return and the conditional I wrote doesn't do anything because it runs before the data returns. How do I call the function after my data loads? I tried everything on the ionicView Docs. I also tried window.onload but that doesn't work. Thanks for your help in advance.
var firebaseRef = new Firebase("https://app.firebaseio.com/files/0/" + $stateParams.theId);
firebaseRef.once('value', function(dataSnapshot){
var dumData = dataSnapshot.val().data;
//this is just an integer
if (dumData > 3){
document.getElementById("pic").style.backgroundImage = 'url(img/pic2.png';
}
//Please ignore syntax errors as they do not exist in original code
Your issue is not related with ionic.
once returns a promise. So you should use the success callback to handle your data.
From Firebase once documentation:
// Provide a failureCallback to be notified when this
// callback is revoked due to security violations.
firebaseRef.once('value',
function (dataSnapshot) {
// code to handle new value
}, function (err) {
// code to handle read error
});

Cloud code not working

i am new at parse..trying code..trying to run a trigger required in my project.but not able to track not even i am getting any error.
i am using cloud code i.e triggers...
what i want to do is, after update or save i want to run a trigger which will a column in a class with value of 200.
Parse.initialize('APPLICATION_ID', 'JAVASCRIPT_KEY');
Parse.Cloud.afterSave("match_status", function(request)
{
var query = new Parse.Query('Wallet');
query.set("wallet_coines_number", 200);
query.equalTo("objectId", "FrbLo6v5ux");
query.save();
});
i am using afterSave trigger in which match_status is my trigger name. after that i making a object called query of Wallet class. This object will set column 'wallet_coines_number' with the value 200 where objectId is FrbLo6v5ux. after that i used save function which will execute query.
Please guide me if i am wrong, or following wrong approach.
Thank You !
Have you read the Parse documentation on Cloud Code ?
The first line of your code is only relevant when you are initialising Parse JavaScript SDK in a web page, you do not need to initialise anything in Parse cloud code in the main.js file. Also you cannot use a query to save/update an object. A query is for searching/finding objects, when you want to save or update an object you need to create a Parse.Object and save that.
So you code should become something like:
Parse.Cloud.afterSave("match_status", function(request) {
var wallet = new Parse.Object('Wallet');
wallet.set("wallet_coines_number", 200);
wallet.set("objectId", "FrbLo6v5ux");
wallet.save();
});

get method not working on Parse current User

I am making an express app with Parse. In my cloud code, I am trying to get an attribute of the current user, but it is returning me undefined. My code looks like following:
app.get('/home/subscriptions',function(req,res){
Parse.Cloud.useMasterKey();
var user = Parse.User.current();
var ifstud = user.get("isStudent");
console.log('student: ' + ifstud); // undefined
console.log('id: ' + user.id); // OK. works fine.
}
I am able to retrieve the id of the user as above but not able to call the get method on user. In their API reference, they have mentioned that Parse.User.current() returns a Parse.Object, so I think in user I have _User object and I should be able to call all methods supported by a Parse.Object.
What might be the issue here?
Thanks
I figured it out and putting this answer for future reference to users who visit this question.
The Parse.User.current() returns only a pointer to the user and not the complete user object. To get access to all fields of the user, fetch the entire object using the fetch method.
var fullUser;
Parse.User.current.fetch().then(user){
fullUser = user;
}).then(function(){
// Place your code here
});
I think it should be: var ifstud = Parse.User.get("isStudent");

Anonymous Users with Parse SDK

I'm aware that Parse.com does not support Anonymous Users for the Javascript SDK which is what I'm using now. I've asked a Parse staff member what an alternative for those using the Parse Javascript SDK and want to have something like the Anonymous User feature offered for the Parse ios SDK might be. I was told by the Parse staff member: "This is not officially supported yet, but you might be able to implement something similar by generating a random username and password that is stored in localStorage for this user". Now, right now, the following code allows me to save information to my Parse database
var MYObject = Parse.Object.extend("MYObject");
var myObject = new MYObject();
var SomeStuff = "Test";
myObject.set("RECORD",SomeStuff);
myObject.save(null, { success: function(myObject)
{ //alert alert('New object created with objectId: ' + myObject.id); }
This creates a new class then adds "RECORD" and "Test". It works. Yet this is saved without needing a username or password at all. I'm wondering why just allowing users to save data like that can't be sufficient instead of having the Anonymous User feature Parse offers or in my case, an alternative solution for the Anonymous User feature since Anonymous User is not supported by the Parse Javascript SDK which is what I'm using. Is the reason the Anonymous User feature offered in the first place a matter of security? Should I resort to the alternative solution given to me by Parse staff or is it unnecessary?
can you just generate a 'random' or a 'guid' and then plug that into User.username with password&email undefined... On the insert of that user, you have a valid Parse.User object that is anonymous. The return from the User.insert() is 'token' which never expire. You can use cookie to store the {"token":val, "username":val}.
Without a passwd, you never log the user in and will always be forced to call cloudcode where you can pass in the user's token (-H "X-Parse-Session-Token: rcid...") in place of a validated session established with 'login'.
I've used this technique in REST API where i want to onboard users without any input to text fields. They provide no info , only agreeing to use an anonymous cloud account.
I know this answer is very late, but it's relevant because nothing has changed. There is no Class for Anonymous users in the Parse JS SDK.
The reason why you can create, save, edit and delete objects without having an User Session is because you can create objects that anyone can use; I.E, "Public Objects". You can set ACL credentials on these objects as well, but you will not be associating new objectsIds with userObjectIds and therefore will only be able to update said objects in Cloud Code using your apps MasterKey.
var Foo = Parse.Object.extend("Foo");
var foo = new Foo();
foo.set("message", "Hello Foo");
foo.save().then(function(foo){
//foo was saved
//anyone can edit it right now
//make it disappear into a black hole
//in other words, nobody can edit without Master Key
var acl = new Parse.ACL();
acl.setPublicReadAccess(false); //nobody can read it
acl.setPublicWriteAccess(false);//nobody can write it
foo.setACL(acl);
return foo.save();
}).then(function(foo){
//since foo was returned, we can still read it, but
//we cannot edit it anymore...
foo.set("message", "cannot update without Master Key");
return foo.save();
}).then(function(foo){
//this will not run
}, function(error){
//catch error for cannot update foo
log(error);
});
In this example, I start off by creating the Foo object. Then I update the message column and save it. The saved object is returned and I create an ACL that will prevent anyone for reading and writing to Foo. Then I set Foos ACL and save it again. The saved object is returned and I try to update the message column again. This time an error occurs and the error callback logs the error. This happens because I cannot update foo anyone, unless I use the Master Key and that must take place in Cloud Code.
Parse.Cloud.useMasterKey();
foo.save().then.... //after second return of foo.save() above

Categories

Resources