I have a class called Item that is filtered by PeriodId. There are many periods - but we only need to look at one at a time. I want to present the user with an initial data load (say where PeriodId==1). I then want the user to be able to query/filter on other periods.
If the user selects PeriodId==2, I want the entityManager to query the local cache, and if the data is there, return that data. If it's not in the local cache, I want it to query the server, and add the set where PeriodId==2 to the cache. If the user then clicks on PeriodId==1, that data should already be in the cache and not round-trip to the server.
Using the code below, I am hitting the server every time I select a period (even if I just toggle back and forth). Is there a pattern that solves this... I do NOT know the primary keys here.
var getItems = function (myObservable, periodId, forceRemote) {
var pId = periodId ? periodId : 1;
var query = entityQuery.from('Item')
.orderBy(orderBy.items)
.where("PeriodId", "==", pId);
if (!forceRemote) {
var r = getLocal(query);
if (r) {
if (r.length > 3) {
myObservable(r);
return Q.resolve();
}
}
}
return manager.executeQuery(query)
.then(querySucceeded)
.fail(queryFailed);
function querySucceeded(data) {
if (myObservable) {
myObservable(data.results);
}
}
};
function getLocal(query) {
try {
return manager.executeQueryLocally(query);
} catch(e) {
// set was not found in local cache, return null - forcing trip to server
return null;
}
}
UPDATE:
Incorporating Jay's suggestion, (I had to rename 'param' to 'pId', 'q' to 'query', reset the queryParamCache if forceRemote==true, and I had to prepend the FetchStrategy with 'breeze.' ):
var queryParamCache = {};
var getItems = function(myObservable, periodId, forceRemote) {
if (forceRemote) {
queryParamCache = {};
}
var pId = periodId ? periodId : 1;
var query = entityQuery.from('Item')
.orderBy(orderBy.items)
.where('PeriodId', '==', pId);
var isInCache = queryParamCache[pId];
if (isInCache && !forceRemote) {
query = query.using(breeze.FetchStrategy.FromLocalCache);
} else {
queryParamCache[pId] = true;
query = query.using(breeze.FetchStrategy.FromServer);
}
return manager.executeQuery(query)
.then(querySucceeded)
.fail(queryFailed);
function querySucceeded(data) {
rosterObservable(data.results);
}
};
function queryFailed(error) {
var msg = 'Error retreiving data. ' + error.message;
logError(msg, error);
throw error;
}