How to push deletions to local breeze caches? - breeze

If I'm using breezejs and one client deletes a record from their cache and it saves to the server, then another client comes along with that record still in their cache, how do I get the second client's cache to update and remove the record that has been hard deleted?

It's a good question and we don't have a really great answer. We refer to these as 'ghost' entities, and the approach we have taken to them in the past is that if you requery for an entity ( or entities) by id, and they are not returned then you can safely remove them from the entityManager. (The code below has not been tested, but should give you the idea);
function checkIfDeleted(entityManager, entities) {
origEntities = entities.slice(0);
var q = EntityQuery.fromEntities(entities);
entityManager.executeQuery(q).then(function(data) {
var foundEntities = data.entities;
foundEntities.forEach(function(e, ix) {
if (entities.indexOf(e)) {
origEntities.splice(ix,1)
}
});
if (origEntities.length > 0) {
origEntities.forEach(function(e) {
entityManager.removeEntity(e);
});
}
});
}

Related

Why isn't my updated observable List reflected in the template?

I've got:
my-app
community-list
On attached, my-app gets the user and loads the app.user. In the meantime, community-list is attached (even before app.user is loaded) and so I haven't been able to get the user's starred communities yet. Therefore, the solution I'm working on is as follows.
In community-list.attached():
app.changes.listen((List<ChangeRecord> records) {
if (app.user != null) {
getUserStarredCommunities();
}
});
Elsewhere in community-list is said metho:
// This is triggered by an app.changes.listen.
void getUserStarredCommunities() {
// Determine if this user has starred the community.
communities.forEach((community) {
var starredCommunityRef = new db.Firebase(firebaseLocation + '/users/' + app.user.username + '/communities/' + community['id']);
starredCommunityRef.onValue.listen((e) {
if (e.snapshot.val() == null) {
community['userStarred'] = false;
} else {
community['userStarred'] = true;
}
});
});
}
Note that communities is an observable list in community-list:
#observable List communities = toObservable([]);
Which is initially populated in community-list.attached():
getCommunities() {
var f = new db.Firebase(firebaseLocation + '/communities');
var communityRef = f.limit(20);
communityRef.onChildAdded.listen((e) {
var community = e.snapshot.val();
// If no updated date, use the created date.
if (community['updatedDate'] == null) {
community['updatedDate'] = DateTime.parse(community['createdDate']);
}
// snapshot.name is Firebase's ID, i.e. "the name of the Firebase location"
// So we'll add that to our local item list.
community['id'] = e.snapshot.name();
// Insert each new community into the list.
communities.add(community);
// Sort the list by the item's updatedDate, then reverse it.
communities.sort((m1, m2) => m1["updatedDate"].compareTo(m2["updatedDate"]));
communities = communities.reversed.toList();
});
}
In summary, I load the list of communities even before I have a user, but once I have a user I want to update each community (Map) in the list of communities with the userStarred = true/false, which I then use in my community-list template.
Alas, it doesn't seem like the List updates. How do I achieve this?
This whole app.changes.listen business is expensive. What's the proper practice in a case like this, where an element is loaded before I load objects (like app.user) that will modify it in some way.
1)
toList() creates a copy of the list. You need to apply toObservable again to get an observable list.
communities = toObservable(communities.reversed.toList());
This also assigns a new list to communities which is covered by #observable.
I think it should trigger anyway
2) You update your communities explicitly. It shouldn't be necessary to listen for changes. You can call a method containing
if (app.user != null) {
getUserStarredCommunities();
}
explicitly each time you change the list.
You also call Firebase for each community when a change in communities occurs. I don't know Firebase but it seems you send a request to a server each time which is of course expensive.
You should remember for what user+community combination you already made the call and use the remembered result instead.
With app.changes.listen you listen to any updated of any #observable field in your component. If you have other observable fields beside communities this method might be called too often.
If you are only interested in changes to communities you should put this code into a method like
communitiesChanged(oldVal, newVal) {
if (app.user != null) {
getUserStarredCommunities();
}
}
but the better option is to not listen to changes and another method name and call it explicitly as state above anyways if possible.

Added Entitties don't change entityState after entityManager.saveChanges()

I create a new Entity in EntityManager like this:
var newCust = manager.createEntity('Customer', { Name: 'MyNewCustomer' });
it's Id is correctly generated. On a Button-Click I save the Entity on the Server:
manager.saveChanges([newCust]).then(function (saveResult) {
alert('saved!');
}
Now everything works perfect BUT, the Entity in newCust keeps it's EntityState "Added". It doesn't change to "Unchanged".
I've debugged a little and found out, that in the function "mergeEntity(mc, node, meta)" of breeze, where the following code happens - no entity is found (eventhough the key it searches is the same Id - the Id-Fixup worked correctly):
var targetEntity = em.findEntityByKey(entityKey);
So everytime I save my new Entity, a new Entity will be created in my EntityManager. When I reload the page, the entity is flagged correctly and works. The only problem is, that a new entity will be saved everytime I save changes.
Thanks for any help!
Edit 1:
I found the problem and I'm not sure what exactly Breeze expects of me. When my ContextProvider saves the Entity it sends a DB-Update-Command (for all the properties) and then returns. The problem is, that the Id of the saveResult-Object is still the "tempId" and not the real one - so when Breeze on Client-Side receives the object it doesn't find it in the entityManager anymore because the Key-Fixup happened already.
What exactly is Breeze expecting to receive from the saveResult? A representation of the object as it is in the Database at this moment? - would make sense but I don't find it documented.
Edit 2:
It looks like I'm not able to replace the object in the saveWorkState.saveMap (EntityInfo info.Entity is readonly). What I would like to do is create the newly added object and return this object instead of the one that breeze sent me. I have calculated values on the newly created object and the new "real" Id. What the NoDB-Sample seems to do is just overwrite the Id for the newId but any other properties are not changing. Maybe I'm not using this mechanism right?
To make sure, that all EntityInfos that are returned in my SaveResult are the latest representation of the Database I just clear the saveWorkState.SaveMap-Lists
saveWorkState.SaveMap[n].Clear()
and add the new representations
saveWorkState.SaveMap[n].AddRange(newEntityInfos);
and for every Entity that is Added or Modified I create a new EntityInfo with the object that is returned by the Database
private EntityInfo SaveEntity(List<KeyMapping> keyMap, EntityInfo info) {
EntityInfo result = info;
switch (info.EntityState) {
case EntityState.Added: {
// CreateInDatabase
// Possible changes in object properties happen (for calculated values)
...
var newObj = GetObjectAgainFromDatabase(info.Entity);
keyMap.Add(new KeyMapping() { EntityTypeName = bu.RuntimeClass.FullName, TempValue = (MyObject)info.Entity.Id, RealValue = newObj.Id });
result = CreateEntityInfo(newObj, EntityState.Added);
break;
}
case EntityState.Deleted: {
// Delete in Database
// EntityInfo doesn't have to change
break;
}
case EntityState.Modified: {
// Update in Database
result = CreateEntityInfo(bu.WrappedPOCO, EntityState.Modified);
break;
}
default: //EntityState.Detached, EntityState.Unchanged
break;
}
return result;
}
Any comments on this solution are welcome!

BreezeJS - Using expand

I am querying the server to get an entity with expand
function _loadIncidents() {
var deffered = Q.defer(),
queryObj = new breeze.EntityQuery().from('Incidents').expand(['Deployments', 'IncidentComments', 'DTasks', 'ExtendedProperties', 'IncidentEvents']);
dataRepository.fetchEntitiesByQuery(queryObj, true).then(function (incidents) {
var query = breeze.EntityQuery.from("DTasks"),
incidentIds = dataRepository.getEntitiesByQuerySync(query);
deffered.resolve();
}, function(err) {
deffered.reject(err);
});
return deffered.promise;
};
I am getting the results and all is fine, how ever when I query breeze cache to get the entities - I am getting empty collection. So when using expand does the expanded entities are added to the cache?
Yes the related entities identified in the expand should be in cache ... if the query is "correct" and the server interpreted your request as you intended.
Look at the payload of the response from the first request. Are the related entities present? If not, perhaps the query was not well received on the server. As a general rule, you want to make sure the data are coming over the wire before wondering whether Breeze is doing the right thing with those data.
I do find myself wondering about the spelling of the items in your expand list. They are all in PascalCase. Are they these the names of navigation properties of the Incident type? Or are they the names of the related EntityTypes? They need to be former (nav property names), not the latter.
I Had problem with the navigation property - as I am not using OData webapi not using EF , there is problem with the navigation properties so for the current time i just wrote
Object.defineProperty(this, 'Deployments', {
get: function () {
return (this.entityAspect && this.entityAspect.entityManager) ?
this.entityAspect.entityManager.executeQueryLocally(new breeze.EntityQuery("Deployments").
where('IncidentID', 'eq', this.IncidentID)) :
[];
},
set: function (value) { //used only when loading incidents from the server
if (!value.results) {
return;
}
var i = 0,
dataRepository = require('sharedServices/dataRepository');
for (i; i < value.results.length; i++) {
dataRepository.addUnchangedEntity('Deployment', value.results[i]);
}
},
enumerable: true
});

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?

Saving an array of new entities via breeze context "saveChanges"

If I have an entity that contains a 1:n collection of another entity then what is the correct way to save the collection?
I've got to this (code not finalised/checked yet):
return datacontext.savechanges([parentEntity]).then(function() {
for (var i=0;i < childArray.length;i++) {
var newChildEntity;
return datacontext.makeNewChildEntity(newChildEntity).then(function() {
newChildEntity.parentID(parentEntity().id());
...
//set other newChildEntity properties
...
return datacontext.savechanges([newChildEntity]).then(function() {
//set finished flag and exit function...
}
}
}
}
"datacontext" is an async module with various exposed methods including creating a new childEntity.
Whereas I haven't tested this yet, it kind of logically works for me, but am I right to be looping around in the createEntity/modifyEntity/saveEntity loop for each new child object I want to add to the collection of childEntities? Is this the only way to do it or is there a way of doing all childEntities in one hit?
The "parentID" is an identity field - store generated so I have to wait for the intitial parent save to finish before I can use the returned ID.
Edited to add: I don't think I need to have a "then" on the end of the async newChildEntity save, do I? I need it to be async still so it can go off and loop through multiple childEntities quickly as the dependent bit is the id from the parent record that's already generated. All the child records share the same parentID so I can set off multiple saves without waiting for the saveChanges method to respond, right?
Breeze's EntityManager.saveChanges can save any number of entities in a single call, which is substantially more performant than trying to call saveChanges once per entity.
Also, I'm not sure why your makeNewChildEntity needs to be asynchronous, Breeze's EntityManager.createEntity itself is synchronous, so I think that all you need to do is something like this.
return datacontext.savechanges([parentEntity]).then(function() {
var listOfEntities = [parentEntity];
for (var i=0;i < childArray.length;i++) {
// synchronous makeNewChildEntity
var newChildEntity = datacontext.makeNewChildEntity();
newChildEntity.parentID(parentEntity().id());
...
//set other newChildEntity properties
...
listOfEntities.push(newChildEntity);
}
// alternatively use datacontext.savechanges(listOfEntities).then(...)
return datacontext.savechanges().then(function() {
//set finished flag and exit function...
}
}
}

Resources