Duplicate Parse.com User objectId to another column - ios

I am trying to write some Cloud Code for Parse that upon creation of a new _User, it will copy that user's objectId, append it, and then put the resulting value in a new column called SubscriptionObject. The code I have tried is:
Parse.Cloud.afterSave(Parse.User, function(request, response) {
Parse.Cloud.useMasterKey(MYMASTERKEY);
var theObject = Parse.User.current().id
var newObject = 'User_' + theObject;
request.object.set("SubscriptionObject", newObject);
response.success();
});
However, the SubscriptionObject key never gets set.

What does console.log('User_' + theObject); log? It may not be a string. I think it may something like "Object object"
Try using concat.
var userString = 'User_';
var newObject = userString.concat(request.user.id);
I used request.user.id because I'm not familiar with Parse.User.current().id
Unrelated, but I've never had to pass my master key into the call. I just call Parse.Cloud.useMasterKey(); Perhaps we have some differences where it is necessary. Just looking out so you don't have to publish your master key as a global variable if it's not necessary.

Related

getProperty of entity in Odata model in SAPUI5 not working

I have a oData model with entities : Order, OrderInformation. There is 1 : 1 an association between Order and OrderInformation.
Now in the view, based on a value in OrderInformation, I should hide / display a button.
In the controller, following logic to get the value of OrderInformation->appUrl does not work but I can read the property of entity 'Order'.
Init: function(){
// Not working
var prop = this.getView().getModel().getProperty("/OrderInformations('"+ this._orderId + "')/appUrl");
// Working
var prop = this.getView().getModel().getProperty("/Orders('"+ this._orderId + "')/orderType");
}
In transaction /IWFND/GW_CLIENT, following query gives me correct value
/sap/opu/odata/sap/<<ServiceURL>>/OrderInformations('132123')/appUrl
I also tried with the attachRequestCompleted but still no success.
Init:function(){
var oModel = this.getView().getModel();
oModel.attachRequestCompleted(function(oEvent){
var myval = model.getProperty("/OrderInformations('"+ this._orderId + "')/appUrl");
});
}
Can someone provide any idea what can be going wrong ?
BR
Nilesh
You can use the oModel.read function to trigger a request to the backend, within the success handler you read the result of the response and process the received data
var test = oModel.read("OrderInformations('" + this._orderId + "')", {
success: function(oData, response) {
var appUrl = oData.result.appUrl; //response.data.appUrl also works
// do something
},
error: function (oError) {
// Error handling on failed response
}
});
API reference: https://openui5beta.hana.ondemand.com/#docs/api/symbols/sap.ui.model.odata.ODataModel.html#read
I don't understand this line you wrote:
In the controller, following logic to get the value of
OrderInformation->appUrl does not work but I can read the property of
entity 'Order'.
Order is another Entity with a property and the addressing for this works like described above?
Did you init your model like this:
/sap/opu/odata/sap/<<ServiceURL>>/Order? Is OrderInformation a related entity of Order? If yes extend the read with the Navigation property of the odata service which defines the relationship between the two Entities
I hope this answers you question, if anything left, let me know
Best regards

Prevent duplicate objects but allow Update with Cloud-Code and Parse.com as backend

I've an issue with Cloud Code.My problem is explained as:
I've a class "MyClass"
I want only one object saved in my backend referring to a particular property ("myID")
If a user try to save this object and there is not any with the same "myID" save it
If a user try to save this object and THERE IS ALREADY ONE with the same "myID" update the field ("address") for the existing object.
I try to this using this code:
var MyObject = Parse.Object.extend("MyClass");
Parse.Cloud.beforeSave("MyClass", function(request, response) {
if (!request.object.get("myID")) {
response.error('A MyObject must have a unique myID.');
} else {
var query = new Parse.Query(MyClass);
query.equalTo("myID", request.object.get("myID"));
query.first({
success: function(object) {
if (object) {
object.set('address',request.object.get("address"));
object.save().then(function () {
response.error('Updated existing MyObject address');
},function (error) {
response.error("Error: " + error.code + " " + error.message);
});
} else {
response.success();
}
},
error: function(error) {
response.error("Could not validate uniqueness for this MyObject object.");
}
});
}
});
But this doesn't works and in my Parse.com Log says:
Result: Error: 142 Error: 124 Too many recursive calls into Cloud Code
I know can I achieve what I want?
You have a beforeSave method that is triggered when an object of MyClass should be stored. If this method detects that the object searched for already exists, it modifies this object and tries to store it. But this triggers again the beforeSave method, and so on, an infinite loop.
You could do it on the client side: Check, if the object exists. If not, create it, but if so, add an entry to it. But you should be aware that you will have a problem: If more than 1 client executes this code at the same time, they could all find out that the object does not exist yet, and more than 1 object will be created.
I would thus create such an object right from the beginning, and use the atomic operation addUniqueObject:forKey: to add entries to an array.
You don't need to save the object in beforeSave - any changes you've made to request.object will be saved when you call response.success()

Parse Cloud Code - How to add object from another class to user

My application displays data to my users via the Parse.com. I am using their iOS sdk with their cloud code. I am required to use cloud code to add an object to my user. What I'm looking for is something like:
[PFCloud callFuction:#"addObjectToUser" withParameters:params];
And my parameters would be the userID and the the object ID of the object I want associated with that user ID.
How would I achieve this in JavaScript?
In order to change anything on a user object in parse (without being changed by the user themselves) it must be done through cloud code and by using the useMasterKey(). Assuming that you have set up your params like this:
NSDictionary *params = #{userID: #"12345", objectID: #"67890"};
You can save objects to a user with the master key like this:
//Add Object To User's "objectsAddedToUser" array
Parse.Cloud.define("addObjectToUser", function(request, response) {
// (1)
var userID = request.params.userID;
var objectID = request.params.objectID;
// (2)
var query = new Parse.Query(Parse.User);
query.equalTo("userID", userID);
query.first().then(function (user) {
// (3)
Parse.Cloud.useMasterKey();
// (4)
user.add("objectsAddedToUser", objectID);
// (5)
user.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
}, function (error) {
response.error(error);
});
});
(1) Get the parameters that you passed in.
(2) Query the database and retrieve the user that needs to be updated.
(3) IMPORTANT Use the master key to unlock privileges.
(4) Add the objectID to the user.
(5) Save to Parse.
Adding cloud function is explain in detail here, there is an example as well which explain how you can write java-script function to manipulate or add data.

Breeze - How to Load Navigation property from cache

I am getting a single entity by using a method fetchEntityByKey, after that I am loading navigation property for the entity by entityAspect.loadNavigationProperty. But loadNavigationProperty always make a call to the server, what I am wondering if I can first check it from cache, if it is exist then get it from there otherwise go the server. How is it possible? Here is my current code
return datacontext.getProjectById(projectId)
.then(function (data) {
vm.project = data;
vm.project.entityAspect.loadNavigationProperty('messages');
});
Here is a function that I encapsulated inside datacontext service.
function getProjectById(projectId) {
return manager.fetchEntityByKey('Project', projectId)
.then(querySucceeded, _queryFailed);
function querySucceeded(data) {
return data.entity;
}
}
Also, how is it possible to load navigation property with some limit. I don't want to have all records for navigation property at once for performance reason.
You can use the EntityQuery.fromEntityNavigation method to construct a query based on an entity and a navigationProperty . From there you can execute the resulting query locally, via the EntityManager.executeQueryLocally method. So in your example once you have a 'project' entity you can do the following.
var messagesNavProp = project.entityType.getProperty("messages");
var query = EntityQuery.fromEntityNavigation(project, messagesNavProp);
var messages = myEntityManager.executeQueryLocally(query);
You can also make use of the the EntityQuery.using method to toggle a query between remote and local execution, like this:
query = query.using(FetchStrategy.FromLocalCache);
vs
query = query.using(FetchStrategy.FromServer);
please take a look here: http://www.breezejs.com/sites/all/apidocs/classes/EntityManager.html
as you can see fetchEntityByKey ( typeName keyValues checkLocalCacheFirst ) also have a third optional param that you can use to tell breeze to first check the manager cache for that entity
hope this helps

Breeze-Unreferenced Entity in Manager

I am developing a Single Page App using Hot Towel Template, using breeze...and I have come across a peculiar problem, and I am unable to figure out the internal working which causes it...
I have a Programmes table, and the Programmes table has a foreign key to Responses, so the structure of Programmes is:
Id, ResponseID, Name and Date
and the Page has Name and Date, the foreign comes from RouteData.
and for one ResponseId in Programmes table, I want to save only on Programme.
So, when user comes to this page, it check the Programmes table that if it has an Entry for that particular Response Id, if yes, it goes in Edit case and if not it goes to Add a new entry case.
To achieve this, what I am doing is below:
var objTempProgramme = ko.observable();
var objProgramme = ko.observable();
function activate(routeData) {
responseId = parseInt(routeData.responseId);
// Create a Programme Entity
objProgramme(datacontext.createProgramme());
// Fill in a Temporary Observable with Programmes data
datacontext.getEntitiesDetailsByRelativeId('responseID', responseId , 'Programmes', objTempProgramme, true).then(function(){
// Check if Programmes Exists
if (objTempProgramme() != null && objTempProgramme() != undefined) {
// What I am doing here is filling my Programmes Entity with data coming from database (if it is there)
objProgramme(objTempProgramme());
} else {
// The Else Part assigns the Foreign Key (ResponseId) to my Entity Created above
objProgramme().responseID(responseId);
}
});
}
In datacontext.js:
var createProgramme = function () {
return manager.createEntity(entityNames.programme);
}
var getEntitiesDetailsByRelativeId = function (relativeIdName, relativeId, lookupEntity, observable, forceRefresh) {
var query = entityQuery.from(lookupEntity).where(relativeIdName, "==", relativeId);
return executeGetQuery(query, observable, forceRefresh);
};
Now when I call manager.saveChanes on my page, I would Expect objProgramme to be saved, in any case, be it edit or be it save,
but what breeze is doing here is that though it is filling objTempProgramme in objProgramme, but it is also leaving the entity objProgramme unreferenced with its manager, so that when I call save, it tries to save that entity too (2 entities in total, objProramme and one unreferenced one), but that entity does not have foreign key set and it fails..but my question is why?
Assigning one entity to another does not mean all its properties get assigned to another? And why is that unreferenced entity present?

Resources