iced-coffee-script (
https://github.com/maxtaco/coffee-script)
"_" is my lodash library with some convenience mixins
object simply keeps a potentially expensive query result in program memory, example at bottom
# vim: set expandtab tabstop=2 shiftwidth=2 softtabstop=2
_ = require 'taky'
cache = require 'memory-cache'
module.exports = class CacheLoop
fn: no
key: 'key'
prefix: 'cachel'
interval: '1 min'
constructor: (@obj) ->
this[k] = v for k,v of obj
@fn = @use if @use
@fn = @refresh if @refresh
@interval = @every if @every
if !@fn
throw new Error 'You must provide a function value for "fn"'
@_cycle()
_.every @interval, => @_cycle()
read: ->
if hit = cache.get (@prefix or '') + ":#{@key}"
hit
else
null
val: -> @read()
value: -> @read()
_cycle: ->
if _.type(@fn) is 'function'
@fn (err,res) =>
if !err
cache.put ((@prefix or '') + ":#{@key}"), res
else
# todo: use backup storage (redis,memcached)
###
c = new Cacher {
fn: (cb) ->
cb new Date().getTime()
interval: '5 seconds'
}
_.every '1s', -> log c.read()
1406767835607
1406767835607
1406767835607
1406767835607
1406767835607
1406767840608
1406767840608
1406767840608
1406767840608
1406767840608
1406767845609
1406767845609
###