I have defined a Parse Cloud Code function for beforeSave below.
Parse.Cloud.beforeSave(Parse.User, function(request, response) {
Parse.Cloud.useMasterKey();
var publicACL = new Parse.ACL();
publicACL.setPublicReadAccess(true);
publicACL.setPublicWriteAccess(true);
request.object.setACL(publicACL);
response.success();
});
This code runs correctly whenever I save a new Parse.User. However, when I try to update a pre-existing Parse.User, the code does not execute. Any thoughts? Below is the code I am using to update my user.
function updateStudentTypes(id, studentType, chkBox) {
var query = new Parse.Query(Parse.User);
query.get(id, {
success: function(user) {
var typeList = user.get("studentType");
if(!chkBox.checked)
typeList = removeStudentType(typeList, studentType);
else
typeList = addStudentType(typeList, studentType);
user.set("studentType", typeList);
user.save(null, {
success: function(user) {
//alert('New object created with objectId: ' + user.id);
},
error: function(user, error) {
alert('Failed to update user: ' + error.message);
}
});
},
error: function(object, error) {
alert("Error querying user: " + error);
}
});
}
Add this to the beginning of your updateStudent method:
Parse.Cloud.useMasterKey();
Edit: I thought your code was cloud code, not client side javascript.
Related
Below is my cloud code in which I am attempting to use to create a Friend Database, Both the first and the third function work fine however the AcceptFriendRequest function times out as if there is no server there with the error code 100. I am very lost as this happens 100% of the time. All help is appreciated.
Parse.Cloud.define("AddFriendRequest", function (request, response) {
var FriendRequest = Parse.Object.extend("FriendsIncoming");
var FRequest = new FriendRequest();
var user = request.user;
var query = new Parse.Query(Parse.User);
query.equalTo("username", request.params.username);
query.find({
success: function (people) {
if(people.length == 0)
{
response.success(-5);
return;
}
var person = people[0];
FRequest.set("OwnerID", user.id);
FRequest.set("TargetFriend", person.id);
FRequest.set("Status", 0);
var query = new Parse.Query("FriendsIncoming");
query.equalTo("OwnerID", user.id);
query.equalTo("TargetFriendID", person.id);
query.find({
success: function (results) {
if (results.length > 0) {
response.success(1);
return;
}
FRequest.save(null, {
success: function (Friend) {
response.success(2);
},
error: function (Friend, error) {
response.error(3);
}
});
response.error(-2);
},
error: function () {
response.error(-1);
}
});
}
,
error: function (Friend, error) {
response.error(-4);
}
});
});
Parse.Cloud.define("AcceptFriendRequest", function (request, response) {
var user = request.user;
var query = new Parse.Query("FriendsIncoming");
query.equalTo("OwnerID", user.id);
query.equalTo("TargetFriendID", request.params.TargetFriendID);
query.find({
success: function (results) {
if (results.length > 0) {
response.success(1);
return;
}
FRequest.save(null, {
success: function (Friend) {
response.success(2);
},
error: function (Friend, error) {
response.error(3);
}
});
response.error(-2);
},
error: function () {
response.error(-1);
}
});
});
Parse.Cloud.define("RetrieveFriends", function (request, response) {
var query = new Parse.Query("FriendsAccepted");
var results = [];
query.find().then(function (Friends) {
for (var i = 0; i < Friends.length; i++) {
results.push(Friends[i]);
}
// success has been moved inside the callback for query.find()
response.success(results);
}, function (error) {
// Make sure to catch any errors, otherwise you may see a "success/error not called" error in Cloud Code.
response.error("Could not retrieve Posts, error " + error.code + ": " + error.message);
});
});
It seems like the FRequest in the AcceptFriendRequest is not initialized...
add this in the inside of the function. The timeout on parse.com is 15 seconds for cloud function and for afterSave 3 secs. They might changed it though cause they are shutting down
var FriendRequest = Parse.Object.extend("FriendsIncoming");
var FRequest = new FriendRequest();
I am kinda new to the whole cloud code and I am having a bit of trouble fetching some data.
So what I basically want is a function that by giving it a 'username' that is located in the Parse.User database, it will return the user's objectId which I will then use to locate the user's session in the Parse.Session, from there I will get the installationId which I will then use in the Parse.Installation to get the device token.
Note: I have written a function that keeps only 1 session active per user.
My issue:
The Query of Parse.Session has a result which only contains 3 objects, and the installationId is not included,therefor I can not find out what is the installation id and then use it to search the Parse.Installation to get the device token.
input example:
Input:
{"from":"user1",
"msg":"hello",
"title":"Whatever title",
"to":"user2"}
Here is the existing code I currently have which doesn't work.
Parse.Cloud.define('gcm', function(request,response){
var username = request.params.to;
console.log("usr "+username);
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo('username', username);
userQuery.find({
success: function(results){
var objectId = results[0].id;
console.log("obj id "+objectId);
var user = new Parse.User();
//Set your id to desired user object id
user.id = objectId;
var sessionQuery = new Parse.Query(Parse.Object.extend('Session'));
sessionQuery.include(user);
sessionQuery.find({
success: function(results1){
console.log("result classname type: "+typeof(results1[0]));
var installId = results1[0].installationId ; //here is the value which I want from the result, but the object is type of _Session which does not have installationId.
console.log("inst id "+installId);
var InstallationQuery = new Parse.Query(Parse.Installation);
InstallationQuery.equalTo('installationId',installId);
InstallationQuery.find({
success: function(results2){
var deviceToken = results2[0].get("deviceToken");
console.log("token "+deviceToken);
Parse.Cloud.httpRequest({
method: "POST",
url: " https://gcm-http.googleapis.com/gcm/send",
headers: {'Authorization' : 'key=AIzaSyDj4ISkLW7CzAQEQEhTsq3JYZK5OP8tSzY',
'Content-Type' : 'application/json'},
body: {
"data":
{
"title": request.params.title,
"msg": request.params.msg
},
"to" : deviceToken
},
success: function(httpResponse) {
response.success("Message Sent!");
console.log(httpResponse.text);
},
error: function(httpResponse) {
response.error("Error, Something went wrong.");
console.log("error 4: " + httpResponse.status);
}
});
},
error: function(error) {
//error
console.log("error 3: " + error);
}
});
},
error: function(error) {
//error
console.log("error 2: " + error);
}
});
},
error: function(error) {
//error
console.log("error 1: " + error);
}
});
});
I have trouble updating a set of values in my cloud code. I have tried .save() seperately and .saveAll() but the class doesn't get updated in Parse and I get errors returned.
What I am trying to do is to get all messages from class ChatMessages which has a pointer to the Parse user and Chat class. When the method is called, the class column readAt needs to be updated to the current date. I call my method from an iOS (objective-C) app.
This is the latest version of my method:
Parse.Cloud.define("markChatAsReadForRoomAndUser", function(request, response) {
var errorMsg;
var roomName;
var _ = require('underscore.js');
var userPointer = new Parse.User.current();
if (!request.params.roomName) {
errorMsg = "Chat room needs to be identified";
} else {
roomName = request.params.roomName;
}
console.log("Checking chats for userID: " + userPointer.id);
if (!userPointer.id) {
var emptyUserMsg = "User has to be provided";
if (errorMsg) {
errorMsg = errorMsg + emptyUserMsg;
} else {
errorMsg = emptyUserMsg;
};
}
if (errorMsg) {
response.error(errorMsg);
}
var chatQuery = new Parse.Query("Chat");
chatQuery.equalTo("roomName", roomName);
chatQuery.find({
success: function(results) {
if (results.length > 0) {
var chat = results[0];
console.log("Found chat with ID: "+chat.id);
var chatMessagesQuery = new Parse.Query("ChatMessage");
chatMessagesQuery.equalTo("chat", chat);
chatMessagesQuery.notEqualTo("fromUser", userPointer);
chatMessagesQuery.equalTo("readAt", undefined);
chatMessagesQuery.find().then(function(chatMessagesQueryResults) {
_.each(chatMessagesQueryResults, function(result) {
result.set("readAt", new Date());
console.log("Setting readAt for chat message " + result.id + " which has toUser " + result.get("toUser"));
});
return Parse.Object.saveAll(chatMessagesQueryResults,{
success: function(list) {
console.log("Success updating objects");
},
error: function(error) {
console.log("Error updating objects: " + error);
},});
}).then(function(results) {
response.success(results);
console.log("Update for reatAt for chat is successfull");
}, function(error) {
response.error(error);
console.log(error);
});
} else {
response.error("No rooms found");
console.log("No rooms found");
}
},
error: function(error) {
response.error("Room name not found");
console.log(error);
}
});
});
Log output:
E2015-07-19T09:13:48.483Z]v337 Ran cloud function markChatAsReadForRoomAndUser for user CZwQL4y751 with:
Input: {"roomName":"room_czwql4y751_uoc7rjxwpo"}
Result: {"code":101,"message":"object not found for update"}
I2015-07-19T09:13:48.540Z]Checking chats for userID: CZwQL4y751
I2015-07-19T09:13:48.593Z]Found chat with ID: gfvAkirqTs
I2015-07-19T09:13:48.647Z]Setting readAt for chat message ZiWUIdUtUm which has toUser undefined
I2015-07-19T09:13:48.648Z]Setting readAt for chat message YHEBLpR04U which has toUser undefined
I2015-07-19T09:13:48.649Z]Setting readAt for chat message 0wZ4LQd8ZC which has toUser undefined
I2015-07-19T09:13:48.650Z]Setting readAt for chat message MYsYGyXI0k which has toUser undefined
I2015-07-19T09:13:48.751Z]Error updating objects: [object Object]
I2015-07-19T09:13:48.752Z]{"code":101,"message":"object not found for update"}
E2015-07-19T09:13:49.042Z]v337 Ran cloud function markChatAsReadForRoomAndUser for user CZwQL4y751 with:
Input: {"roomName":"room_czwql4y751_uoc7rjxwpo"}
Result: {"code":101,"message":"object not found for update"}
Class:
The query can be vastly simplified by making a chatMessages query relational to chats matching the user and room criteria. The code structure can be improved by not mixing callback and promise styles, and by separating logical chunks into small, promise-returning functions.
Stripping away some of the debug instrumentation you added, we get (untested, of course)...
function unreadChatMessagesInRoom(roomName, excludeUser) {
var query = new Parse.Query("ChatMessage");
query.notEqualTo("fromUser", excludeUser);
query.doesNotExist("readAt");
var chatQuery = new Parse.Query("Chat");
chatQuery.equalTo("roomName", roomName);
query.matchesQuery("chat", chatQuery);
return query.find();
}
Parse.Cloud.define("markChatAsReadForRoomAndUser", function(request, response) {
var _ = require('underscore.js');
var user = request.user;
unreadChatMessagesInRoom(request.params.roomName, user).then(function(chatMessages) {
console.log(chatMessages.length + " chat messages found");
_.each(chatMessages, function(chatMessage) {
chatMessage.set("readAt", new Date());
});
return Parse.Object.saveAll(chatMessages);
}).then(function(results) {
response.success(results);
}, function(error) {
response.error(error);
});
});
I'm trying to retrieve roles for a desired user where I know if objectId.
exports.User.getUserRole = function(userId, success, error)
{
Parse.Cloud.useMasterKey();
console.log("getUserRole method");
var query = new Parse.Query(Parse.User);
query.
equalTo("objectId", userId)
.find({
success: function(user){
console.log("SUCCESS 1");
console.log(user);
var queryRole = new Parse.Query(Parse.Role);
queryRole
.equalTo("users", user)
.find({success: function(roles){
console.log("SUCCESS 2");
success(roles);
},
error: function(_errorRole){
console.log("FAIL 2");
console.log(_errorRole);
error(_errorRole);
}
});
},
error: function(_error){
console.log("FAIL 1");
error(_error);
}
});
But I've this strange error in the CloudCode logs:
FAIL 2 // My console.log
{"code":102,"message":"equality needs a value instead of
[map[__type:Pointer className:_User objectId:qjsmwxQ4KQ]] "}
The following function seems to only work for my Current user, any other ObjectId that I type into the input will return a Post (Bad Request) error in the console.
var query = new Parse.Query(Parse.User);
var userInput = $('#inputObject').val();
query.equalTo("objectId", userInput);
query.first({
success: function(result) {
console.log(result.id);
result.set('money', 20);
result.save();
},
error: function(error) {
console.log("None found.");
}
});
The problem with this is that the Parse user object is only modifiable by the current user. You can get around this by creating a Cloud Code function, which modifies the money value for the intended user. Note, the cloud code function must call Parse.Cloud.useMasterKey(); Source
CloudCode Function:
Parse.Cloud.define("setMoney", function(request, response) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.equalTo("objectId", request.params.userId);
query.first({
success: function (result) {
console.log(result.id);
result.set('money', 20);
result.save();
response.success();
},
error: function (error) {
console.log("None found.");
response.error(error);
}
});
});
JavaScript Call
Parse.Cloud.run("setMoney", {userId: userInput}, {
success: function(result) {
// Success
},
error: function(error) {
// Error
}
});