Last active
September 18, 2015 04:43
-
-
Save ray-peters/41b00fcdff4583740f95 to your computer and use it in GitHub Desktop.
Protected Storage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* QuickStorage and ProtectedStorage | |
* @brief A caching control mechanism | |
* @author Ray Peters <[email protected]> | |
*/ | |
function QuickStorage(){ | |
this._cache = {}; | |
} | |
QuickStorage.prototype.setItem = function( key, val ) { | |
this._cache[ key ] = val ? JSON.stringify( val ) : val; | |
}; | |
QuickStorage.prototype.getItem = function( key ) { | |
var item = this._cache[ key ]; | |
if ( item === undefined ) { | |
// Nothing here | |
return null; | |
} | |
return item ? JSON.parse( item ) : item; | |
}; | |
QuickStorage.prototype.removeItem = function( key ) { | |
delete this._cache[ key ]; | |
}; | |
QuickStorage.prototype.empty = function(){ | |
delete this._cache; | |
this._cache = {}; | |
}; | |
QuickStorage.prototype.state = function( data ) { | |
if ( data === undefined ) { | |
// Getter | |
return { "data": JSON.stringify( this._cache ) }; | |
} else { | |
// Setter | |
var newCache; | |
try { | |
newCache = data.data ? JSON.parse( data.data ) : {}; | |
} catch ( e ) { | |
console.info( "Trying to set invalid JSON object in QuickStorage." ); | |
} | |
delete this._cache; | |
this._cache = newCache || {}; | |
} | |
}; | |
var ProtectedStorage = function( authFn ) { | |
var cache, _authFn, ownerMap; | |
if ( !authFn || typeof authFn !== "function" ) { | |
return undefined; | |
} | |
cache = new QuickStorage(); | |
_authFn = authFn; | |
ownerMap = {}; | |
return { | |
"setItem": function( key, val ) { | |
cache.setItem( key, val ); | |
ownerMap[ key ] = _authFn(); | |
}, | |
"getItem": function( key ) { | |
if ( ownerMap[ key ] !== _authFn() ) { | |
// Don't own the item, destroy the entry | |
cache.removeItem( key ); | |
delete ownerMap[ key ]; | |
return null; | |
} | |
return cache.getItem( key ); | |
}, | |
"removeItem": function( key ) { | |
cache.removeItem( key ); | |
}, | |
"state": function( data ) { | |
if ( data === undefined ) { | |
// Getter | |
return { | |
"authFn": _authFn, | |
"ownerMap": ownerMap, | |
"cache": cache.state() | |
}; | |
} else { | |
// Setter | |
_authFn = data.authFn; | |
ownerMap = data.ownerMap; | |
cache.state( data.cache ); | |
} | |
}, | |
"empty": function(){ | |
cache.empty(); | |
} | |
}; | |
}; | |
var paneStorage = ProtectedStorage( ( function(){ | |
var hashRegex = /(#![^&]*)/; | |
return function(){ | |
var hash = window.location.hash, | |
ret = hash.match( hashRegex ); | |
return ret ? ret[0] : hash; | |
}; | |
})() ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment