Cache API

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.

Restrictions

  • Only objects which can be represented by JSON can be cached
  • An object can be cached up to a maximum of 1 hour (1-3600 second)
  • A cache post may be maximum 100 000 characters
    • Posts larger then the maximum will be fetched but not cached
  • A cache may contain a maximum of 1 000 000 characters

Accessing a cache

A cache can be either local or shared.

  • A local cache is private to all instances of the WebApp or RESTApp
  • A shared cache can be accessed by all WebApps and RESTApps on the site
    • To access a shared cache a global namespace must be provided
// 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');

Methods

get(key, TTL, callback)

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 });
  });
})();

purge(key)

Removes a value from the cache


Argument

Description

key

A key to remove