Using SparkCache

SparkCache allows you to cache JavaScript objects. SparkCache is designed for short-lived objects that are frequently accessed, it is not designed to serve as a persistent data store.

This topic provides some guidelines for working optimally with SparkCache.

Understanding SparkCache

SparkCache is designed as a data cache so it's important to bear in mind these two common aspects of a caching utility:

Protecting against Null Results from Cache

Here's how to ensure your cached objects aren't expired and disrupt your setup with a null result.

In the following example, we've already used SparkCache to store an object called versionNumber. Now, we run some code to protect ourselves against unexpected null results when we try to access the cached object:

//Attempt to retrieve the latest cached app version number
var data = Spark.getCache().get("versionNumber");

//Check if the data is cached
if(data == null){
    //If no data exists, return an error. Object would have no been cached or it has expired
    Spark.setScriptError("ERROR", "Could not determine version");
    //Or attempt to load the value from somewhere else, possibly a module that retrieves the value from a metadata collection
} else{
    //If object exists in cache, access it. In this example we're accessing an object named 'data' and retrieving the string 'version'
    Spark.setScriptData("version", data.version);