Parse Cloud Code function get deviceToken By username - javascript

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

Related

Creating an Asana Task using a POST http request

I'm trying to use the asana-api to create a Task using a POST http request but I keep getting a 400 bad request as a response.
I managed to get data from the Asana-api using ( a GET request ), but I'm having trouble sending data to Asana with ( a POST request )
I'm using the 'request' module to do the api call
here's the error message :
`{"errors":[{
"message":"Could not parse request data,invalid JSON",
"help":"For more information on API status codes and how to handle them,
read the docs on errors: https://asana.com/developers/documentation/getting-started/errors"}
]}`
Here's my code:
testTask(){
var taskName = "Test Name for a Test Task"
var workspaceID = "123456789"
var projectID = "123456789"
var assigneeID = "123456789"
var parentID = null
this.createTask(taskName, workspaceID, projectID, assigneeID, parentID)
}
createTask(taskName, workspaceID, projectID, assigneeID, parentID){
var token = "0/1234abcd5678efgh9102ijk"
var bearerToken = "Bearer " + token
var task = {
data: {
assignee: "me",
notes: "test test test test",
workspace: workspaceID,
name: taskName,
projects: [projectID],
parent: parentID
}
}
var options = {
"method" : "POST",
"headers" : {"Authorization": bearerToken},
"contentType": "application/json",
"payload" : JSON.stringify(task)
}
try {
var url = "https://app.asana.com/api/1.0/tasks";
request.post(url, options, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
}
catch (e) {
console.log(e);
}
}
I also tried a different implementation :
createTask(){
var token = "0/1234abcd5678efgh9102ijk"
var bearerToken = "Bearer " + token
var options = {
"method" : "POST",
"headers" : {"Authorization": bearerToken},
}
try {
request.post("https://app.asana.com/api/1.0/tasks?workspace=1234567&projects=765534432&parent=null&name=taskName&assignee=me", options, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
}
catch (e) {
console.log(e);
}
}
Based on the examples provided by the request module, it appears that your options object uses payload as a key, but it should be body.

Find objects with field value (this is a pointer)

I have class say 'inspection' and there is a field name property (this is a pointer) . I am trying to retrieve a record by field value but getting nothing as a result. I am using following code
getInspectionByProperty = function(req) {
console.log(req.body.propertyId)
var query = new Parse.Query("Inspection");
query.include('property');
query.equalTo('property', req.body.propertyId);
query.find({
success: function(data) {
console.log('in success');
console.log(data);
// Successfully retrieved the object.
},
error: function(error) {
console.log('in error')
console.log("Error: " + error.code + " " + error.message);
}
});
};
I am getting this error in parse log
Error: 102 pointer field property needs a pointer value
How can i get the record .Thanks in advance
Here what i try and thats work for me.
getInspectionByProperty = function(req) {
console.log(req.body.propertyId)
var query = new Parse.Query("Inspection");
query.include('property');
query.equalTo("property", {
"__type": "Pointer",
"className": "Property",
"objectId": propertyId
});
query.find({
success: function(data) {
console.log('in success');
console.log(data);
// Successfully retrieved the object.
},
error: function(error) {
console.log('in error')
console.log("Error: " + error.code + " " + error.message);
}
});
};

Retrieve roles for user with user objectID in Cloud Code

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]] "}

Parse Cloud Code beforeSave not running on update

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.

Parse, Function only works for the current user

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

Categories

Resources