Sam
Sam

Reputation: 14586

breezejs: confused with fetching entity from database vs from cache

consider the following code:

function getPersonById(personId, type) {

 var p1 = new breeze.Predicate("Id", "==", personId);    
 var p2 = new breeze.Predicate("Type", "==", type);        
 var query = breeze.EntityQuery.from("Contacts").where(p1.and(p2))

 if (!manager.metadataStore.hasMetadataFor(service.serviceName)) {
      return manager.fetchMetadata().then(function () {
          return manager.executeQuery(query.using(service));
      });
 } else {
      var fromCache = manager.getEntityByKey('Contact', personId);
       if (fromCache)
             return Q.resolve(fromCache);
        return manager.executeQuery(query.using(service));
 }
}
  1. Am I doing things the right way ? It seems to me that I have to write a lot of boiler-plate code just for fetching an entity. I had to make sure the metadata was known, and then if the entity is already in cache or not.

  2. I'm facing an issue because if executeQuery is called, then the return value is an array. However if getEntityByKey is called, then the return value is an Entity. How can I deal with that in an elegant way ? Is there a way to force executeQuery to return a single Entity rather than an array ? (I'm expecting only one returned value anyway)

Upvotes: 0

Views: 475

Answers (1)

PW Kad
PW Kad

Reputation: 14995

Your metadata test shouldn't be necessary for each query. If you add a fail method that handles any errors (such as no metadata) you can write that only once, but in reality if whatever service type JavaScript file you are using is loaded metadata should always be there. If you are moving datacalls to the view models then I would recommend rethinking that strategy.

the way you are doing your cache check is optional. Remember that there are two ways to query from cache - executeQueryLocally and setting the fetchStrategy. There are some instances where you will want to go refresh data from the server so I would definitely recommend trying to pull from cache first in each query and only going to the database on a needed basis. Generally I only have two methods for all my data retrieval, for each entity, although if you are tricky you can probably reduce that to sharing queries as well. Your queries are most efficient when you can reuse them for different orderBy's, where clauses, etc...

Last, if you want to return only a single entity just do it lklike you would any other array - catch the returned array results before sending them back and filter it down to something like data.results[0]. You could also query and then use a filter to find the first entity that meets sine criteria.

Upvotes: 1

Related Questions