can-connect/cache-requests/cache-requests
Caches reponse data and uses it to prevent future requests or make future requests smaller.
cacheRequests( baseConnection )
Overwrites getListData to use set logic to determine which data is already in cacheConnection or needs to be loaded from the base connection.
It then gets data from the cache and/or the base connection, merges it, and returns it.
Use
Use cache-requests in combination with a cache
like can-connect/data/memory-cache/memory-cache or can-connect/data/localstorage-cache/localstorage-cache. For example,
var cacheConnection = connect([
require("can-connect/data/memory-cache/memory-cache")
],{});
var todoConnection = connect([
require("can-connect/data/url/url"),
require("can-connect/cache-requests/cache-requests")
],{
cacheConnection: cacheConnection,
url: "/todos"
})
This will make it so response data is cached in memory. For example, 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 original request's data will be used.
Using Algebra
cache-requests can also "fill in" the data the cache is mising 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 configuration, cache-requests will only request {start: 11, end: 20}.
That configuration looks like:
var algebra = new set.Algebra( set.comparators.range("start","end") );
var cacheConnection = connect([
require("can-connect/data/memory-cache/memory-cache")
],{algebra: algebra});
var todoConnection = connect([
require("can-connect/data/url/url"),
require("can-connect/cache-requests/cache-requests")
],{
cacheConnection: cacheConnection,
url: "/todos",
algebra: algebra
})
Notice that cacheConnections often share many of the same options as the
primary connection.