Parse Server Cloud Code Update User - javascript

I am attempting to update a parse user field and the function stops in the middle of it:
Parse.Cloud.define("modifyAdminStatus", function(request, response) {
var userQuery = new Parse.Query(Parse.User);
var isAdmin = request.params.adminStatus;
console.log("isAdmin:" + isAdmin);
userQuery.equalTo("username", request.params.username);
userQuery.find({ useMasterKey: true,
success: function(user) {
console.log(user.length);
console.log("Got User")
console.log(user);
user.set("isAdmin", isAdmin);
console.log("Set Status");
user.save(null, {useMasterKey: true,
success: function(user) {
response.success();
},
error: function(error) {
response.error(error.message);
}
});
},
error: function(error) {
response.error(error.message);
}
});
});
I dont get any syntax errors, when i run the code i get:
1
Got User
[ ParseUser { _objCount: 2, className: '_User', id: '2vigcitsl6' } ]
in my console. However, it seems to stop the code after i attempt to set the admin status. I have tried running it using useMasterKey but that didnt do anything so maybe I'm missing something and where the useMasterKey should go?

The answer is:
query.find({
... code here
});
Returns an array, using query.first (or selecting one object from the array) instead will get one object and allow you to set things on it.

When you're trying to save the user, parse expects two parameters. The first should be an object containing any changes, and the second should be the save options.
So in your case, simply change your save to user.save (null, {useMasterKey:true, success...})
The way you have it now would create a column on Parse.User entitled useMasterKey, if permissions allow.

Related

Parse fetching User inside of hook not working

i am using this
var USER = Parse.Object.extend("_User");
var query = new Parse.Query(USER);
query.get(request.user.id, {
success: function(results) {
console.log(results);
// results has the list of users with a hometown team with a winning record
},
error : function(error){
console.error(error);
}
to fetch the user making the request. (In this case it's a after save hook)
For any reason "results" just containing:
ParseObjectSubclass { className: '_User', _objCount: 2, id: 'zW3o9c2wbY' }
But i need access to other fields of this user - how can i do so?
Best, Nico
see query documentation the include method is what you are looking for.
Fyi, here's how I would write it:
new Parse.Query(Parse.User)
.include('ptrFieldIWantReturned')
// master key shouldn't be needed, but I can't be sure of your config.
.get(request.user.id, { useMasterKey: true })
.then(
user => console.log('got: ' + user.id),
error => console.error('uh-oh: ' + error.message)
);

How to prevent current user get notified?

I'm making an app that allows user to like and comment on other user post. I'm using Parse as my backend. I'm able to notified user everytime their post liked or commented. However if current user like or comment on their own post this current user still notified. How can I prevent this?
Here is the js code that I use:
Parse.Cloud.afterSave('Likes', function(request) {
// read pointer async
request.object.get("likedPost").fetch().then(function(like){
// 'post' is the commentedPost object here
var liker = like.get('createdBy');
// proceed with the rest of your code - unchanged
var query = new Parse.Query(Parse.Installation);
query.equalTo('jooveUser', liker);
Parse.Push.send({
where: query, // Set our Installation query.
data: {
alert: message = request.user.get('username') + ' liked your post',
badge: "Increment",
sound: "facebook_pop.mp3",
t : "l",
lid : request.object.id,
pid: request.object.get('likedPostId'),
lu : request.user.get('username'),
ca : request.object.createdAt,
pf : request.user.get('profilePicture')
}
}, {
success: function() {
console.log("push sent")
},
error: function(err) {
console.log("push not sent");
}
});
});
});
If I understand the context of where this code is correctly,
I recommend checking
if request.user.get("username") != Parse.CurrentUser.get("username")
Before sending out the push notification
Where is your cloud function being called from? If you're calling it from your ios code, then before you call the cloud code function, just prelude it with something like this:
if (PFUser.currentUser?.valueForKey("userName") as! String) != (parseUser.valueForKey("userName") as! String)

Save changes to a user that is not currently logged in

In my _User class I have a column named check. The initial value of the column for someUser(some other saved user) is true and as a currentUser(currently logged in user) I want to be able to change that value to false.
Unfortunately for security reasons, Parse won't allow me to save any changes to a user that is not currently logged in, and I get an error: User cannot be saved unless they have been authenticated via logIn or signUp. I already tried adding ACL to Public read and write, but It didn't work.
I know I need to use Cloud Code and the Master Key to get it sorted out.
There is this post: Can't write non current user objects by PFUser currentuser, but I can't figure out the way to adapt it.
Parse.Cloud.define("test_func", function (request, response) {
var user = request.user;
user.increment("blabla", value); //do user stuff
user.save(); // You don't need masterkey to edit your own user object
// Get authentication to edit other user objects
Parse.Cloud.useMasterKey();
// query or get another user
var user2 = ...
user2.increment("blabla", value); // do user2 stuff
user2.save();
// Finish cloud func
response.success("yeeey");
}
If you don't useMasterKey Parse will give error while saving user2
You can use something like this:
Parse.Cloud.define("update_user", function(request, response) {
var query = new Parse.Query(Parse.User);
query.equalTo("objectId", request.params.objectId)
// Queries user to be updated
query.first({
success: function(user) {
user.set("check", request.params.check);
// Updates user (using MasterKey to get permission to update non logged in users)
user.save(null, { useMasterKey: true }).then(function() {
response.success();
}, function(error) {
response.error(error);
});
}, error: function(error) {
response.error(error);
}
});
});
And call the "update_user" function (e.g.: in Objective-C):
NSDictionary *params = #{#"objectId" : user.objectId,
#"check" : #"true"};
[PFCloud callFunctionInBackground:#"update_user" withParameters:params block:^(id object, NSError *error) {
NSLog(#"error: %#", error.userInfo[#"error"]);
}];

Ember data: Rollback createRecord on error

I'm trying to find the best way to avoid adding a record when there's an error using Ember Data:
This is my code:
createUser: function() {
// Create the new User model
var user = this.store.createRecord('user', {
firstName: this.get('firstName'),
lastName: this.get('lastName'),
email: this.get('email')
});
user.save().then(function() {
console.log("User saved.");
}, function(response) {
console.log("Error.");
});
},
I'm validating the schema on backend and returning a 422 Error in case it fails.
If I don't handle the error, the record is added to the site and I also get a console error.
So I did this:
user.save().then(function() {
console.log("User saved.");
}, function(response) {
user.destroyRecord();
});
Which kind of works deleting the record after reading the server response but:
1) I see the record appearing and dissapearing (like a visual glitch to say it somehow).
2) The console error still appears.
Is there a way to better handle this? I mean, is there a way to avoid adding the record when the server returns an error? Is there a way to avoid showing the console error?
Thanks in advance
You'll need to catch the error in the controller and then use deleteRecord() to remove it from the store:
actions: {
createContent() {
let record = this.store.createRecord('post', {
title: ''
});
record.save()
.then(rec => {
// do stuff on success
})
.catch(err => {
record.deleteRecord();
// do other stuff on error
});
}
}

Parse Cloud Code: Delete All Objects After Query

Scenario
I have an app that allows users to create an account, but also allows the user's the ability to delete their account. Upon deletion of their account I have a Cloud Code function that will delete all of the "Post"s the user has made. The cloud code I am using is...
//Delete all User's posts
Parse.Cloud.define("deletePosts", function(request, response) {
var userID = request.params.userID;
var query = new Parse.Query(Parse.Post);
query.equalTo("postedByID", userID);
query.find().then(function (users) {
//What do I do HERE to delete the posts?
users.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
}, function (error) {
response.error(error);
});
});
Question
Once I have the query made for all of the user's posts, how do I then delete them? (see: //What do I do HERE?)
You could use
Parse.Object.destroyAll(users); // As per your code – what you call users here are actually posts
See: http://parseplatform.org/Parse-SDK-JS/api/classes/Parse.Object.html#methods_destroyAll
Also, consider using Parse.Cloud.afterDelete on Parse.User (if that is what you mean by "deleting account") to do cleanups such as these.
Oh, and just to be complete, you don't need the save() routine after destroyAll()
Updates in-line below below your "What do I do HERE..." comment:
NOTES:
You don't need to call the save() method, so I took that out.
This, of course, is merely a matter of personal preference, but you may want to choose a parameter name that makes a little more sense than "users", since you're really not querying users, but rather Posts (that just happen to be related to a user).
Parse.Cloud.define("deletePosts", function(request, response) {
var userID = request.params.userID;
var query = new Parse.Query(Parse.Post);
query.equalTo("postedByID", userID);
query.find().then(function (users) {
//What do I do HERE to delete the posts?
users.forEach(function(user) {
user.destroy({
success: function() {
// SUCCESS CODE HERE, IF YOU WANT
},
error: function() {
// ERROR CODE HERE, IF YOU WANT
}
});
});
}, function (error) {
response.error(error);
});
});

Categories

Resources