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 queryLogic 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 memoryStore = require("can-memory-store");
var dataUrl = require("can-connect/data/url/url");
var cacheRequests = require("can-connect/cache-requests/cache-requests");
var queryLogic = require("can-query-logic");
var todoQueryLogic = new QueryLogic({});
var cacheConnection = memoryStore({queryLogic: todoQueryLogic});
var todoConnection = connect([dataUrl, cacheRequests],{
cacheConnection: cacheConnection,
url: "/todos",
queryLogic: todoQueryLogic
});
Now if today's todos are loaded:
todoConnection.getListData({filter: {due: "today"}});
And later, a subset of those todos are loaded:
todoConnection.getListData({filter: {due: "today", status: "critical"}});
The second request will be created from the original request's data.
QueryLogic Usage
cache-requests
will "fill-in" the cacheConnection
using queryLogic.
For example, if you requested paginated data like:
todoConnection.getListData({filter: {status: "critical"}})
And then later requested:
todoConnection.getListData({})
cache-requests
will only request {filter: {status: ["low","medium"]}}
, merging
that response with the data already present in the cache.
That configuration looks like:
var memoryStore = require("can-memory-store");
var dataUrl = require("can-connect/data/url/url");
var cacheRequests = require("can-connect/cache-requests/cache-requests");
var queryLogic = require("can-query-logic");
var todoQueryLogic = new QueryLogic({
keys: {
status: QueryLogic.makeEnum(["low","medium","critical"])
}
});
var cacheConnection = memoryStore({queryLogic: todoQueryLogic});
var todoConnection = connect([dataUrl, cacheRequests], {
cacheConnection: cacheConnection,
url: "/todos",
queryLogic: todoQueryLogic
})
Note: cacheConnection
shares the same queryLogic configuration as the primary connection.