I am using the following code to get a single entry from parse.com in my corona sdk app. Is there a way to get two entries at the same time, say x1=55.317269 and x1=55.21354. I need the corresponding values for both entries rather than one.
local params = {x1=55.317269}
params.headers = headers
params.body = json.encode ( params )
network.request( "https://api.parse.com/1/functions/getFeatured","POST",getData,params)
The following is my cloud function.
Parse.Cloud.define("getFeatured", function(request, response) {
var query = new Parse.Query("testClass");
query.equalTo("x1", request.params.x1);
query.find({
success: function(results) {
var sum = 0;
sum = results[1].get("y1");
response.success(sum);
},
error: function() {
response.error("movie lookup failed");
}
});
});
Try this -
Parse.Cloud.define("getFeatured", function(request, response) {
var query = new Parse.Query("testClass");
query.containedIn("x1", ARRAY_OF_VALUES_TO_BE_MATCHED);
query.find({
success: function(results) {
// Modify/Create Proper Response Here
respones.success(results);
},
error: function() {
response.error("movie lookup failed");
}
});
});
Related
I am trying to set the message to "Data Loading.." whenever the data is loading in the grid. It is working fine if I don't make an Ajax call. But, when I try to make Ajax Request, It is not showing up the message "Loading data..", when it is taking time to load the data. Can someone please try to help me with this.. Thanks in Advance.
_loadData: function(x){
var that = this;
if(this.project!=undefined) {
this.setLoading("Loading data..");
this.projectObjectID = this.project.value.split("/project/");
var that = this;
this._ajaxCall().then( function(content) {
console.log("assigned then:",content,this.pendingProjects, content.data);
that._createGrid(content);
})
}
},
_ajaxCall: function(){
var deferred = Ext.create('Deft.Deferred');
console.log("the project object ID is:",this.projectObjectID[1]);
var that = this;
console.log("User Reference:",that.userref,this.curLen);
var userObjID = that.userref.split("/user/");
Ext.Ajax.request({
url: 'https://rally1.rallydev.com/slm/webservice/v2.0/project/'+this.projectObjectID[1]+'/projectusers?fetch=true&start=1&pagesize=2000',
method: 'GET',
async: false,
headers:
{
'Content-Type': 'application/json'
},
success: function (response) {
console.log("entered the response:",response);
var jsonData = Ext.decode(response.responseText);
console.log("jsonData:",jsonData);
var blankdata = '';
var resultMessage = jsonData.QueryResult.Results;
console.log("entered the response:",resultMessage.length);
this.CurrentLength = resultMessage.length;
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:resultMessage
});
this.pendingProjects = resultMessage.length
console.log("this testcase store:",resultMessage);
_.each(resultMessage, function (data) {
var objID = data.ObjectID;
var column1 = data.Permission;
console.log("this result message:",column1);
if(userObjID[1]==objID) {
console.log("obj id 1 is:",objID);
console.log("User Reference 2:",userObjID[1]);
if (data.Permission != 'Editor') {
deferred.resolve(this.testCaseStore);
}else{
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:blankdata
});
deferred.resolve(this.testCaseStore);
}
}
},this)
},
failure: function (response) {
deferred.reject(response.status);
Ext.Msg.alert('Status', 'Request Failed.');
}
});
return deferred;
},
The main issue comes from your Ajax request which is using
async:false
This is blocking the javascript (unique) thread.
Consider removing it if possible. Note that there is no guarantee XMLHttpRequest synchronous requests will be supported in the future.
You'll also have to add in your success and failure callbacks:
that.setLoading(false);
I have a job in the parse cloud, inside the job I've a Parse.Cloud.run, when I run this function works fine and parse data base is update, but in the in the cloud job statuses appears failed. Here's my code:
Thanks in advance.
Parse.Cloud.job("updateTopsThreeJob", function(request, status) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query("_User");
query.descending("followersOfMe");
query.limit(3);
query.find({
success: function(results) {
var TestJS = Parse.Object.extend("testJS");
var test = new TestJS();
var listTops = [];
for (var i = 0; i < results.length; i++) {
var object = results[i].get("username");
listTops.push(object);
}
Parse.Cloud.run("updateTopsThree", {objects: listTops}, {
success: function(result) {
status.success("Migration completed successfully.");
response.success(result)
},
error: function(error) {
status.error("Uh oh, something went wrong.");
}
});
response.success(listTops);
},
error: function(error) {
response.error("failed");
}
});
});
Parse.Cloud.define("updateTopsThree", function(request, response) {
var tops = Parse.Object.extend("testJS");
var query = new Parse.Query(tops);
query.get(ObjIDs.topsThreeID(), {
success: function(topsThree) {
topsThree.set("topsThree", request.params.objects);
topsThree.save();
response.success(topsThree);
},
error: function(object, error) {
response.error(error);
}
});
});
The Parse Cloud Code runs much like any other javascript file. In order to declare another function to be called within the parse .js file, such as in this case, you do not need to define the function using Parse syntax. Define and call it just as you would a normal Javascript function.
Use this to call the function within your Parse.job:
updateTopsThree(topThreeObjects);
Define function:
function updateTopsThree(topObjects) {
var tops = Parse.Object.extend("testJS");
var query = new Parse.Query(tops);
query.get(ObjIDs.topsThreeID(), {
success: function(topsThree) {
topsThree.set("topsThree", topObjects);
topsThree.save();
response.success(topsThree);
},
error: function(object, error) {
response.error(error);
}
});
}
Thanks, but finally I´ve solved my problem as follows: I´ve created a cloud function like this:
Parse.Cloud.define("setLikesInDB", function(request, response) {
var query = new Parse.Query("testJS");
query.get(ObjIDs.topsLikesID(), {
success: function(topsThree) {
topsThree.set("topsLikes", "likes");
topsThree.save();
response.success(topsThree)
},
error: function(object, error) {
response.error(error);
}
});
});
And then into my Parse.Cloud.Job I´ve called a cloud function like this:
Parse.Cloud.run('setLikesInDB', {obj : listTops}, {
success: function(result) {
response.success(result);
},
error: function(error) {
response.error('some error')
}
});
This way works fine.
I hope this helps someone else.
I'm attempting to create my first Parse Cloud Code function and am running into an issue:
Parse.Cloud.afterSave("Message", function(request) {
var fromUser = request.object.get("fromUser");
var toUser = request.object.get("toUser");
console.log(fromUser); // user pointer
console.log(toUser); // user pointer
});
As you can see both fromUser and toUser is a pointer when what I actually want is the user objects themselves. What is the best way to do this?
You can create a new query to get user informations.
var query = new Parse.Query(Parse.User);
query.get(request.object.get('fromUser').id, {
success: function(user) {
// What you want with user informations
},
error: function() {}
});
You can try this, but I've never try.
var query = new Parse.Query(Parse.User);
query.equalTo('objectId', request.object.get('fromUser').id);
query.equalTo('objectId', request.object.get('toUser').id);
query.find({
success: function(users) {
// What you want with users information
},
error: function() {}
});
I am too late, but I hope this will work
you can use
Parse.Cloud.beforeSave("Message", function(request, response) { ....
or
Parse.Cloud.afterSave("Message", function(request) { ....
.
this is how to use beforeSave
Parse.Cloud.beforeSave("Message", function(request, response) {
var message = request.object;
var fromUser = message.get("fromUser"); // you must have this User object, if it's null, then the object is null in the table
var toUser = message.get("toUser");
// fromUser and toUser columns must be Pointer<User> and have values
}).catch(function(error) {
response.error("Error finding message " + error.code + ": " + error.message);
});
});
I'm saving some objects into tables on my Parse Data. But I need to add a constraint or make sure that the data i'm trying to insert is unique. I'm using something like the following code. But i want to guarantee that the eventId (that I'm getting from facebook API) is unique in my tables, so i don't have any redundant information. What is the best way to make it work?
var Event = Parse.Object.extend("Event");
var event = new Event();
event.set("eventId", id);
event.set("eventName", name);
event.save(null, {
success: function(event) {
console.log('New object created with objectId: ' + event.eventId);
},
error: function(event, error) {
console.log('Failed to create new object, with error code: ' + error.message);
}
});
Update:
I'm calling it inside a httpRequest. The following is pretty much what I have and I cant figure out just how to call a beforeSave inside it.
Parse.Cloud.define("hello", function(request, response) {
var query = new Parse.Query("Location");
query.find({
success: function(results) {
console.log(results);
var totalResults = results.length;
var completedResults = 0;
var completion = function() {
response.success("Finished");
};
for (var i = 0; i < totalResults; ++i){
locationId = results[i].get("locationFbId");
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/v2.2/'+locationId+'/events?access_token='+accessToken,
success: function(httpResponse) {
console.log(httpResponse.data);
console.log("dsa"+locationId);
for (var key in httpResponse.data) {
var obj = httpResponse.data[key];
for (var prop in obj) {
var eventObj = obj[prop];
if (typeof(eventObj) === 'object' && eventObj.hasOwnProperty("id")) {
var FbEvent = Parse.Object.extend("FbEvent");
var fbEvent = new FbEvent();
fbEvent.set("startDate",eventObj["start_time"]);
fbEvent.set("locationFbId", locationId);
fbEvent.set("fbEventId", eventObj["id"]);
fbEvent.set("fbEventName", eventObj["name"]);
Parse.Cloud.beforeSave("FbEvent", function(request, response) {
var query = new Parse.Query("FbEvent");
query.equalTo("fbEventId", request.params.fbEventId);
query.count({
success: function(number) {
if(number>0){
response.error("Event not unique");
} else {
response.success();
}
},
error: function(error) {
response.error(error);
}
});
});
}
}
}
completedResults++;
if (completedResults == totalResults) {
completion();
}
},
error:function(httpResponse){
completedResults++;
if (completedResults == totalResults)
response.error("Failed to login");
}
});
}
},
error: function() {
response.error("Failed on getting locationId");
}
});
});
So this is occurring in Cloud Code correct? (Im assuming since this is Javascript)
What you could do is create a function that occurs before each "Event" object is saved and run a query to make sure that the event is unique (query based off of "eventId" key, not objectId since the id comes from Facebook). If the event is unique, return response.success(), otherwise return response.error("Event not unique")
EX:
Parse.Cloud.beforeSave("Event", function(request, response) {
if(request.object.dirty("eventId")){
var query = var new Parse.Query("Event");
query.equalTo("eventId", request.object.eventId);
query.count({
success: function(number) {
if(number>0){
response.error("Event not unique");
} else {
response.success();
}
},
error: function(error) {
response.error(error);
}
});
} else {
response.success();
}
});
Parse.Cloud.define("hello", function(request, response) {
var query = new Parse.Query("Location");
query.find({
success: function(results) {
console.log(results);
var totalResults = results.length;
var completedResults = 0;
var completion = function() {
response.success("Finished");
};
for (var i = 0; i < totalResults; ++i){
locationId = results[i].get("locationFbId");
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/v2.2/'+locationId+'/events?access_token='+accessToken,
success: function(httpResponse) {
console.log(httpResponse.data);
console.log("dsa"+locationId);
for (var key in httpResponse.data) {
var obj = httpResponse.data[key];
for (var prop in obj) {
var eventObj = obj[prop];
if (typeof(eventObj) === 'object' && eventObj.hasOwnProperty("id")) {
var FbEvent = Parse.Object.extend("FbEvent");
var fbEvent = new FbEvent();
fbEvent.set("startDate",eventObj["start_time"]);
fbEvent.set("locationFbId", locationId);
fbEvent.set("fbEventId", eventObj["id"]);
fbEvent.set("fbEventName", eventObj["name"]);
// Our beforeSave function is automatically called here when we save it (this will happen every time we save, so we could even upgrade our method as shown in its definition above)
fbEvent.save(null, {
success: function(event) {
console.log('New object created with objectId: ' + event.eventId);
},
error: function(event, error) {
console.log('Failed to create new object, with error code: ' + error.message);
}
});
}
}
}
completedResults++;
if (completedResults == totalResults) {
completion();
}
},
error:function(httpResponse){
completedResults++;
if (completedResults == totalResults)
response.error("Failed to login");
}
});
}
},
error: function() {
response.error("Failed on getting locationId");
}
});
});
This can also be accomplished before ever calling the save by querying and only saving if the query returns with a number == 0.
Summary: For those joining later, what we are doing here is checking to see if an object is unique (this time based on key eventId, but we could use any key) by overriding Parse's beforeSave function. This does mean that when we save our objects (for the first time) we need to be extra sure we have logic to handle the error that the object is not unique. Otherwise this could break the user experience (you should have error handling that doesn't break the user experience anyway though).
I have 2 tables in parse
Memories and Locations with a relation One-To-One, but the pointer is in Location table ( Pointer )
What i need is to read all memories ten by ten with skip and limit and for each memory to atach a property with location object
By now i have this:
var _ = require('underscore.js');
Parse.Cloud.define("feed", function(request, response) {
var memories = Parse.Object.extend("Memories");
var memoriesQuery = new Parse.Query(memories);
memoriesQuery.skip(0);//request.params.skip);
memoriesQuery.limit(10);//request.params.limit);
memoriesQuery.descending("createdAt");
memoriesQuery.include("group");
var parsedResults = [];
memoriesQuery.find().then(function(memories) {
var promise = Parse.Promise.as();
_.each(memories, function(memory) {
promise = promise.then(function() {
var locations = Parse.Object.extend("Locations");
var locationsQuery = new Parse.Query(locations);
locationsQuery.equalTo("memory", memory);
var subPromise = Parse.Promise();
locationsQuery.first().then(function(location) {
memory["location"] = location;
console.log(JSON.stringify(memory) + " ........ " + memory["location"]);
console.log("=============");
parsedResults.push(memory);
subPromise.resolve(memory);
});
return subPromise ;
});
console.log("-----------");
console.log("Promise:" +promise.toString());
});
return promise;
}).then(function(){
response.success(parsedResults);
});
});
I have no clue what to do.. More than 10 hours of tries.
I appreciate any help!
Finally solved!
Maybe it will help somebody.
Solution:
var _ = require('underscore.js');
var memoriesResult = [];
Parse.Cloud.define("feed", function(request, response) {
var promises = [];
var promise = findMemories();
promise.then(function(memories){
console.log("success promise!!");
_.each(memories, function (memory) {
console.log("each");
promises.push(findLocation(memory));
});
return Parse.Promise.when(promises);
}).then(function(){
console.log("Finish");
response.success(memoriesResult);
}, function(error){
console.error("Promise Error: " + error.message);
response.error(error);
});
});
function findMemories(){
console.log("Enter findMemories");
var memories = Parse.Object.extend("Memories");
var memoriesQuery = new Parse.Query(memories);
memoriesQuery.skip(0);//request.params.skip);
memoriesQuery.limit(10);//request.params.limit);
memoriesQuery.descending("createdAt");
memoriesQuery.include("group");
var promise = new Parse.Promise();
memoriesQuery.find().then(function(memories) {
console.log("Memories found!");
promise.resolve(memories);
}, function(error) {
promise.reject(error);
});
return promise;
}
function findLocation(memory) {
console.log("Enter findLocation");
var locations = Parse.Object.extend("Locations");
var locationsQuery = new Parse.Query(locations);
locationsQuery.equalTo("memory", memory);
var promise = new Parse.Promise();
locationsQuery.first().then(function(location) {
console.log("Location found");
memoriesResult.push({"memory": memory, "location" : location});
promise.resolve(memory);
}, function(error) {
promise.reject(error);
});
return promise;
}
After doing some experiments, I've come up with the following requirements and solution:
You want to page through Memories items a page at a time, sorted by their createdAt
You want the Locations related to each memory
You are limited by the fact that the relationship is Locations->Memories
Your first step is to define the query for memories:
var memoryQuery = new Parse.Query('Memories');
memoryQuery.skip(request.params.skip);
memoryQuery.skip(request.params.limit);
memoryQuery.descending('createdAt');
You can now use this query to limit the Locations objects returned. If your links are all setup correctly you will get back 10 records:
var locationQuery = new Parse.Query('Locations');
// limit to only the page of Memory items requested
locationQuery.matchesQuery('memory', memoryQuery);
// include the Memory pointer's data
locationQuery.include('memory');
var memoriesResult = [];
locationQuery.find().then(function(locations) {
var result = _.map(locations, function(location) {
memory: location.get('memory'),
location: location
});
response.success(result);
}, function(error) {
response.error(error);
});
The only issue with the above is that I'm not sure on the order of the returned records, so you might want to re-sort them before returning them. That is extremely simple though with the underscore library.
This will result in 2 queries no matter the page size.