cache-storage
Version:
[ABANDONED] Advanced cache storage for node js
140 lines (98 loc) • 2.48 kB
text/coffeescript
isFunction = (obj) -> return Object.prototype.toString.call(obj) == '[object Function]'
class Cache
= 'files'
= 'tags'
= 'expire'
= 'items'
= 'priority'
= 'all'
= 'YYYY-MM-DD HH:mm'
: null
storage: null
async: null
namespace: null
constructor: (, ) ->
if !instanceof require('./Storage/Storage')
throw new Error 'Cache: storage must be instance of cache-storage/Storage/Storage'
= .async
.cache = @
: (tree = {}, info = {}) ->
FS = require 'fs-mock'
Cache.fs = new FS(tree, info)
return Cache.fs
: ->
if typeof window != 'undefined'
throw new Error 'Testing with fs module is not allowed in browser.'
Cache.fs = require 'fs'
: ->
if Cache.fs == null
Cache.restoreFs()
return Cache.fs
generateKey: (key) ->
hash = 0
if key.length == 0 then return hash
max = key.length - 1
for i in [0..max]
ch = key.charCodeAt(i)
hash = ((hash << 5) - hash) + ch
hash |= 0
return hash
load: (key, fallback = null, fn = null) ->
if && arguments.length == 2
fn = fallback
fallback = null
if
.read(, (err, data) =>
if err
fn(err, null)
else if data == null && fallback != null
else
fn(null, data)
)
else
data = .read()
if data == null && fallback != null
return
return data
save: (key, data, dependencies = {}, fn = null) ->
if isFunction(dependencies)
fn = dependencies
dependencies = {}
key =
if isFunction(data)
data = data()
if
if data == null
.remove(key, (err) ->
if err
fn(err, null)
else
fn(null, data)
)
else
.parseDependencies(dependencies, (err, dependencies) =>
if err
fn(err, null)
else
.write(key, data, dependencies, (err) ->
if err
fn(err, null)
else
fn(null, data)
)
)
else
if data == null
.remove(key)
else
.write(key, data, .parseDependencies(dependencies))
return data
remove: (key, fn = null) ->
return
clean: (conditions, fn = null) ->
.clean(conditions, fn)
return @
module.exports = Cache