Created
March 31, 2016 11:55
-
-
Save lagbox/f169d8e5334b0e1565fade7e945fb42b to your computer and use it in GitHub Desktop.
Expiring Brain Repository
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
# | |
# data structure | |
# { | |
# key: ..., | |
# expires_at: ..., | |
# ... | |
# } | |
# | |
class CacheBrain | |
KEY = 'cache-it' | |
LIFETIME = 5 | |
constructor: (@brain, key, lifetime) -> | |
KEY = key if key | |
LIFETIME = lifetime || @minutes LIFETIME | |
find: (key) -> | |
@all().filter((o) -> o.key is key.toLowerCase())?[0] | |
save: (data, lifetime) -> | |
data.expires_at = Date.now() + (lifetime || LIFETIME) | |
datas = @all data.key | |
datas.push data | |
@set datas | |
data | |
findOrNew: (key) -> | |
@find(key) || @new(key) | |
new: (key) -> | |
key: key.toLowerCase(), created_at: Date.now() | |
remove: (key) -> | |
@set @all key | |
all: (without) -> | |
data = @brain.get(KEY) || [] | |
data.filter (o) -> | |
(o.expires_at > Date.now()) && (without? && (o.key isnt without.toLowerCase()) || true) | |
set: (data) -> | |
@brain.set KEY, data | |
clear: -> | |
@brain.remove KEY | |
# time helpers | |
days: (days) -> (days || 1) * @hours 24 | |
hours: (hours) -> (hours || 1) * @minutes 60 | |
minutes: (minutes) -> (minutes || 1) * @seconds 60 | |
seconds: (seconds) -> (seconds || 1) * 1000 | |
module.exports = CacheBrain |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment