Hoang ND

web developer

Cache your data with Javascript using cacheJS

One of my hybrid mobile app required JSON data and some rendered HTML to be cached to reduce number of requests to the server. The first solution came to my mind was using localStorage. However, it's lack of support for expire time made me looking for other existing libs. There are some good libs out there for caching in Javascript. However, they are either too complicated or don't have the function I needed. 

Requirements for the lib I'm looking for:

Using array as key for storing cache:

It seems a bit strange, but it quite helpful in may case. I had to cache both JSON data and HTML rendered by the same data. It's annoying that I have to think about string key to store these data like "blog_1_json", "blog_1_view_list", "blog_1_view_single". It's likely I will forget the key or make a typo. It would be much better if I could use arrays like this as keys:

{'blogId':1, type:'json'}
{'blogId':1, type:'view', page: 'list'}
{'blogId':1, type:'view', page: 'single'}

Flushing cache using contextual key (foreign key):

Something like remove all blog posts (cache) with author = 'hoangnd' or category = 'javascript'. It happens very often when I have to cache blog posts (JSON data) with category name on it. How do I know which blog post (cache) to flush, I can't flush all the blog post.

cacheJS

So I went ahead and create my own lib, It's a good chance to learn more about Javascript anyway, since it's one of my weakest skill.

The library can be found here: cacheJS

Here are some basic usage:

Installation:

You can use bower or download it directly from github:

bower install cache-js

Saving cache:

// API
cacheJS.set(key, value, ttl, context)
 
// Example
cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', null, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd',categoryId:2});

Retrieving cache:

// API
cacheJS.get(key)
 
// Example
cacheJS.get({blogId: 1,type: 'view'});

Flushing cache

//API
cacheJS.removeByKey(key)
cacheJS.removeByContext(context)
 
// Example
cacheJS.removeByKey({blogId: 1,type: 'view'});
cacheJS.removeByKey({blogId: 2,type: 'view'});
 
cacheJS.removeByContext({author:'hoangnd'});

Switching provider

// API
cacheJS.use(providerName)
 
// Example
cacheJS.use('array');
cacheJS.use('array').set({blogId:1},'<h1>Blog 1</h1>');

Event listener

// API
cacheJS.on(event,callback)
cacheJS.unsubscribe(event,callback)
 
// Example
var listener = function(objectAdded){
    // do something
};
cacheJS.on('cacheAdded', listener);
 
cacheJS.on('cacheRemoved', function(objectRemoved){
    // do something
});
 
cacheJS.unsubscribe('cacheAdded', listener);

Supported events:

  • cacheAdded
  • cacheRemoved

Learn more about it here: https://github.com/hoangnd25/cacheJS