Cache Objects

A friend and I had just completed the 2016 7DRL challenge. During the course of development, I’d been itching to try new ES6 features, specifically that of classes and inheritance.

I’d come up with an idea to create a class whose attributes would be stored locally on the application server, but whose attribute-values would be stored remotely in a memory cache (specifically, Redis).

Tonight I’ve written what I think will become the basis for my ‘next generation’ online roleplaying game, Tempest.

There are three kinds of objects which expose specific functionality: CacheObject, CacheProperty (inherits CacheObject) and CacheHashProperty (inherits CacheObject). Then there’s the Entity, which composes itself automagically, given a set of properties and initialized values.

In a typical JavaScript scenario, you’d have something like:

var myObj = {
attr1: ‘value1′,
attr2: ‘value2′
};

But what if you want to store these in a memory cache (particularly useful for a high-availability system where shared cache is a necessity)?

With my new system, you instantiate an object like so:

var myObj = new Entity(’myentity’, { arg1: ‘value1′, arg2: ‘value2′ });

Then, with this cacheable Entity in hand, we can perform things like:

myObj.arg1.get().then(function(value) { console.log(value); });
myObj.arg2.set(’newValue2′);

The cool trick, however, is when we need to read or write multiple parameters at once:

myObj.get().then(function(theObj) { console.log(theObj); }); // { arg1: ‘value1′, arg2: ‘value2′ }
myObj.set({ arg1: ‘newValue1′, arg2: ‘newValue2′ });

In each case, a promise is returned by the (io)Redis client, that allows a calling function to control program and I/O flow, in normal Node.js style. But what’s truly great is that this class allows any entity to be synced realtime with Redis, as well as provide a meaningful, clear and simple interface for achieving fast memory-cached data storage useful for high-availability applications.

Leave a Reply