cache-requests
Cache response data and use it to prevent unnecessary future requests or make future requests smaller.
cacheRequests( baseConnection )
Provide an implementation of getListData that uses set logic to determine what data is already in the cache and what data needs to be loaded from the base connection.
It then gets data from the cache and the base connection (if needed), merges it, and returns it. Any data returned from the base connection is added to the cache.
Parameters
- baseConnection
{Object}
:can-connect
connection object that is having thecache-requests
behavior added on to it. Should already contain the behaviors that provide the DataInterface (e.g data/url). If theconnect
helper is used to build the connection, the behaviors will automatically be ordered as required.
Returns
{Object}
:
A can-connect
connection containing the methods provided by cache-requests
.
Use
Use cache-requests
in combination with a cache like memory-cache or
localstorage-cache. For example, to make it so response data is cached
in memory:
var memoryCache = require("can-connect/data/memory-cache/");
var dataUrl = require("can-connect/data/url/");
var cacheRequests = require("can-connect/cache-requests/");
var cacheConnection = connect([memoryCache], {});
var todoConnection = connect([dataUrl, cacheRequests],{
cacheConnection: cacheConnection,
url: "/todos"
});
Now if today's todos are loaded:
todoConnection.getListData({due: "today"});
And later, a subset of those todos are loaded:
todoConnection.getListData({due: "today", status: "critical"});
The subset will be created from the original request's data.
Algebra Usage
cache-requests
can also "fill in" the data the cache is missing if you provide it the necessary set algebra.
For example, if you requested paginated data like:
todoConnection.getListData({start: 1, end: 10})
And then later requested:
todoConnection.getListData({start: 1, end: 20})
... with the appropriate algebra configuration, cache-requests
will only request {start: 11, end: 20}
, merging
that response with the data already present in the cache.
That configuration looks like:
var algebra = new set.Algebra( set.props.rangeInclusive("start","end") );
var cacheConnection = connect([memoryCache], {algebra: algebra});
var todoConnection = connect([dataUrl, cacheRequests], {
cacheConnection: cacheConnection,
url: "/todos",
algebra: algebra
})
Note: cacheConnection
shares the same algebra configuration as the primary connection.