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:
- Be prepared for null results:
- Items are cached for a maximum of 30 days. After 30 days, they expire and need to be re-cached. Expired objects will return a null result. If you're using SparkCache, you should therefore be prepared to deal with a null result, which is an optimization to make access to the data faster in most cases.
- Not designed for persistent data storage:
- If the data is permanent and doesn't change, it should probably be stored as metadata (which is also cached in memory, but never expires). Before you use SparkCache, review the likely update cycle of data you're thinking of caching there.
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
require("versionNumber");
} 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);
}