Cache API for apps is introduced with Sitevision 8. It can improve WebApp and RESTApp performance by offering short term in-memory storage of data. This is particularily useful when the WebApp or RESTApp is executing time-consuming tasks, e.g. fetching data from third party over http.
The Cache API is only accessible server-side, i.e. index.js and server-side modules.
Caches resides in a volatile, shared memory and data can be evicted whenever memory resources are scarce.
Caching should be used only when actually needed. This applies for expensive or time-consuming tasks (e.g. data fetched over http).
Caching fast/cheap data is contra productive. The processing overhead (locking, eviction etc) might outweigh presumed performance gains and it will consume/pollute memory for nothing.
A cache can be either local or shared.
// 1.Retrieve an instance of the Cache API
const cache = require('cache'),
// 2. Get the cache
// a) Get local cache
var localCache = cache.getCache();
// b) Get shared cache
var sharedCache = cache.getSharedCache('aGlobalNamespace');
Returns data from a cache, or if there is no data for the provided key; executes a provided callback function used to populate the cache and return the data.
Argument | Description |
---|---|
key | A key to retrive data from |
TTL | Time To Live (max time until the cached post will be deleted) in seconds (1-3600) |
callback | A function executed if no cached data is found for the key. Should be used to populate the cache with data. The return value from the callback function will be cached and returned. |
// Index.js
localOrSharedCache.get('aKey', 10, () => {
// What to do if there is no data in the cache for the requested key
});
A typical scenario where the Cache API will be useful is when the WebApp/RESTApp is executing time-consuming tasks, e.g. fetching data from third party over http. In such a case the call to the REST-API is made inside the callback argument of the get method.
The example below uses a local cache.
// Index.js
(function () {
'use strict';
const router = require('router');
const requester = require('Requester');
const cache = require('cache');
function myCallback() {
let response = {};
requester
.get('https://jsonplaceholder.typicode.com/posts/1/comments')
.done(function (result) {
response = result;
})
.fail(function () {
response = 'No data';
});
return response;
}
router.get('/', (req, res) => {
const localCache = cache.getCache();
const myData = localCache.get('aKey', 10, () => {
return myCallback();
});
res.render('/', { myData });
});
})();
Removes a value from the cache
Argument | Description |
---|---|
key | A key to remove |