Presently I am using Cloud Code along with the masterkey to modify attributes of other users based on actions of current user. I have an attribute requests_from, and I have managed to add items to this array based on the following code:
Parse.Cloud.define('requestUser', function(request, response) {
var userId = request.params.userId,
requestsFrom = request.params.requestsFrom;
var User = Parse.Object.extend('_User'),
user = new User({ objectId: userId });
user.add('requests_from', requestsFrom); //Changed from set to add
Parse.Cloud.useMasterKey();
user.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
});
I have used the above code to add currentUser.objectId to a target user's requests_from column.
However, my issue is now deleting items from requests_from. Once the current user has done an action, I would like to remove currentUser.objectId from requests_from. However, using user.remove or user.delete isn't working. I was wondering if there is another way to accomplish this via Cloud Code?
Thanks
I hope this answer helps you if you haven't already solved it ! Basically, after researching and failing to find anything, it appears that the solution to this is to do the following:
Parse.Cloud.define('removeRequest', function(request,response){
var userId = request.params.userId;
var User = Parse.Object.extend('_User'),
user = new User({ objectId: userId });
var currentUser = request.user;
var relation = user.relation("request");
relation.remove(currentUser);
Parse.Cloud.useMasterKey();
user.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
});
Related
I've got CouchDB setup with Couchperuser. Locally I use PouchDB.
I'm building a mobile application with Cordova. It's about a todo list. with login, so users have there own list.
When I create a new user it automatically makes a new database for this user.
now, when that user is logged in and adds new todo's to his list, they go in the main database because I use :
var db = new PouchDB('http://localhost:5984/main', {skipSetup: true});
What I want to achieve is that the todo created by the specific user goes into his database. for example:
var db = new PouchDB('http://localhost:5984/userdb-41646d696e32', {skipSetup: true});
How can I automatically do this? so the var db = the users database?
I've looked around the internet but could not find anything about this.
Hope someone can help me with this scenario.
EDIT:
I'll add the code that I use for adding the todo:
var db = new PouchDB('http://localhost:5984/main', {skipSetup: true});
function addToDoItem() {
//get info
var toDoTitle = document.getElementById('toDoTitle').value;
var toDoDescr = document.getElementById('toDoDesc').value;
var addItem = {
_id: new Date().toISOString(),
title: ToDotitle,
description: ToDoDescr
};
db.put(addItem ).then(function (result){
console.log("Added to the database");
console.log(result);
}).catch(function (err){
console.log("someting bad happened");
console.log(err);
});
}
Find out, this is the way to fix it. thought of it already but seemed a bit of a cheap solution. anyway, this is the only code example I found on the internet.
dbs.remote.private = pouchDB(DATABASE.URL + "userdb-" + _convertToHex(username), {
auth: {
username: username,
password: password
}
});
I am trying to send a Push Notification through Parse Cloud Code when a certain object has been modified - "dirty"
I think I am almost there, but received an error because I believe am creating a new user instead of querying for one.
Parse.Cloud.beforeSave("Fact", function(request, response) {
var dirtyKeys = request.object.dirtyKeys();
for (var i = 0; i < dirtyKeys.length; ++i) {
var dirtyKey = dirtyKeys[i];
if (dirtyKey === "isValid") {
//send push
// Creates a pointer to _User with object id of userId
var targetUser = new Parse.User();
// targetUser.id = userId;
targetUser.id = request.object.userID;
var query = new Parse.Query(Parse.Installation);
query.equalTo('user', targetUser);
Parse.Push.send({
where: query,
data: {
alert: "Your Fact was approved :)"
}
});
return;
}
}
response.success();
});
I found this post related to my problem. My question now is how to integrate the user query in my beforeSave block. Ideally I would create another function for the user query and place that in my beforeSave block.
**5/14 Update
I took #toddg's advice and fixed the before save. Here is a clearer picture of what I am trying to do and the new error.
A couple points (as #Subash noted in the comments) before I get into the code:
Parse.Push.send is an async operation, so you'll want to ensure you call response.success() after your push send completes. I'm going to deal with this using Promises, as I think they are more flexible than callbacks. If you're not familiar, read about them here
The return in your if statement will likely prevent the response.success() from being called.
Here's my recommended way of doing it:
Parse.Cloud.beforeSave("Fact", function(request, response) {
// Keep track of whether we need to send the push notification
var shouldPushBeSent = false;
var dirtyKeys = request.object.dirtyKeys();
for (var i = 0; i < dirtyKeys.length; ++i) {
var dirtyKey = dirtyKeys[i];
if (dirtyKey === "isValid") {
shouldPushBeSent = true;
}
}
if (shouldPushBeSent) {
//send push
// Creates a pointer to _User with object id of userId
var targetUser = new Parse.User();
// targetUser.id = userId;
targetUser.id = request.object.userId;
var query = new Parse.Query(Parse.Installation);
// We want to pass the User object to the query rather than the UserId
query.equalTo('user', targetUser);
Parse.Push.send({
where: query, // Set our Installation query
data: {
alert: "Your fact was approved"
}
}).then(function(){
// Now we know the push notification was successfully sent
response.success();
}, function(error){
// There was an error sending the push notification
response.error("We had an error sending push: " + error);
});
} else {
// We don't need to send the push notification.
response.success();
}
});
By the way, I'm assuming that you have a column on your Installation class that tracks which user is associated with each Installation.
I want to add an array of current user object ID in to a user's column called "followers". Due to Parse's security reason not allowing modification to non-current user, I'm forced to use cloud code. The problem is I know nothing about JavaScript, so I need help here.
Here's what I would code if no security issue mentioned above:
//add the current user ID to the user(userPassed) that the current user liked
[userPassed addUniqueObject:[PFUser currentUser].objectId forKey:#"followers"];
[userPassed saveInBackground];
To be very specific, I just want to know how to code the above in cloud code. Thanks.
Here you go:
Parse.Cloud.define('functionName', function(request, response) {
var userId = request.params.userId;
var me = Parse.User.current();
var user = new Parse.User();
user.id = userId;
user.addUnique('followers', me);
return user.save(null, {useMasterKey: true}).then(function(user) {
response.success('Succeed');
}, function(error) {
console.error(error);
response.error('Failed');
});
});
I would like to get the list of users ordered by name and with the new users first.
I've used the documentation reference: http://quickblox.com/developers/Users#Sort
I've trying this code but it is not working at all:
function QBlistUsers(page) {
var userParams = {};
var page = currentPage;
{userParams.perPage = itemsPerPage;}
{userParams.pageNo = page;}
{userParams.order = ['desc','string','full_name'];}
//{userParams.order = 'desc+string+full_name';} // I've try this too, instead of the previous line
//load new rows per page
QB.users.listUsers(userParams, function(err, response){...}
The response is simply ignoring the param "order". I'm I doing something wrong?
thanks for helping
Look at new version of JS SDK 1.2.0:
http://quickblox.com/developers/Javascript
var params = {
order: { sort: 'desc', field: 'full_name' },
per_page: itemsPerPage,
page: page
};
QB.users.listUsers(params, function(error, response){
// callback function
});
Current version of WebSDK supports only 'in' parameter from Users filters. But we are already working on new version which will have all these filter cases. I think, through two / three days it will be released.
Try passing the order parameter like below and let me know whether it is working or not.
QB.users.listUsers({ order:'desc'+'string'+'full_name'}, function(error, response){
if(error) {
console.log(error);
} else {
// Success
}
});
I want to update a field within the User class without being logged in as a user. From reading online and other responses people say I should use the 'masterkey' to do so. Here is my cloud code where I have added in the master key. The code is executed but when I go to my data browser the totalScore and predictions values are still the same and not updated to the new values.
Parse.initialize("key", "key");
Parse.Cloud.define("userUpdate", function(request, response) {
Parse.Cloud.useMasterKey();
var publicReadACL = new Parse.ACL();
publicReadACL.setPublicWriteAccess(true);
request.object.setACL(publicReadACL);
var User = Parse.Object.extend("User");
var query = new Parse.Query(User);
query.equalTo("username", request.params.username);
query.find({
success: function(user) {
user.set("totalScore", request.params.totalS);
user.set("totalPredictions", request.params.totalG);
user.save()
},
error: function() {
response.error("f");
}
});
});
Any help would be massively appreciated.
Hopefully you've figured this out by now, but if you haven't...I would first say check to make sure that you're passing the "totalScore" and "totalPredictions" as numbers. If you pass them as strings and Parse is expecting a Number, it won't update. And generally, I believe it's best practice to query the user class as follows:
var query = new Parse.Query(Parse.User);
query.get(user.objectId, {
success: function(userAgain) {
userAgain.set("totalScore", totalScore);
userAgain.save(null, {
error: function(userAgain, error) {
// This will error, since the Parse.User is not authenticated
}
});
}
});
Then of course you'd still need to include the master key stuff etc...