Playing around with Typescript/Javascript decided to post a client-side cache method using HTML5 localStorage.
Starting with a mock how it should work the cache usage:
export class userController {
public findUsers(id: string) {
var key: string = 'users:' + name;
// fetch from cache
var cache = new Cache.LocalStorageCache();
var data = cache.get(key);
// null = not in cache
if (data == null) {
// Make API Call
var request = new API.Request("/api/v1/users/", "get", {
"id": id
});
request.addCallback((response: API.Response) => {
var data = response.getData(); // store in cache
cache.set(key, data);
this.useUsers(data);
});
request.execute();
} else {
// CACHE HIT
this.useUsers(data);
}
private function useUsers(data: any) {
// do usefull stuff
// like display on box/html
}
}
Cache interface must follow:
interface CacheInterface {
get($key);
set($key, $value, $ttl);
delete($key);
exists($key);
}
One possible implementation:
export class LocalStorageCache implements CacheInterface {
/**
* determine if browser supports localStorage
* @returns {boolean}
*/
public hasCache(): boolean {
return window['localStorage'] !== null;
}
/**
* gets value for one key, null if not found
* @param key
* @returns (string) content of key
*/
public get(key: string): string {
var object = JSON.parse(localStorage.getItem(key));
if (object != null) {
if (this.isExpired(object)) {
// no need to delete, will be replaced
// this.delete(key);
return null;
} else {
return object.value;
}
} else {
// not on localStorage
return null;
}
}
/**
* checks if a item has expired
* @param item
* @returns {boolean}
*/
public isExpired(item: string): boolean {
var item_timestamp: number = item.timestamp;
var now_timestamp: number = new Date().getTime();
var ttl: number = item.ttl;
return ((now_timestamp - item_timestamp) > ttl * 1000);
}
/**
* store one value in localStorage
* @param key unique key to store this item
* @param value string to store
* @param ttl time to live in seconds
*/
public set(key: string, value: string, ttl: number = 60): void {
// @todo check ttl
var object = {value: value, ttl: ttl, timestamp: new Date().getTime()}
localStorage.setItem(key, JSON.stringify(object));
}
/**
* deletes a item on storage
* @param key
*/
public delete(key: string): void {
localStorage.removeItem(key);
}
/**
* checks if a item exists in storage
* @param key
* @return (boolean) true if exists, false otherwise (also when ttl expired)
*/
public exists(key: string): boolean {
var object = JSON.parse(localStorage.getItem(key));
return (object == null || this.isExpired(object));
}
}