memory-cache
Memory based cache library, with two-way expiration, tags and events.
Usage
Note: Any function that accepts an array of key/tag names, will also accept a space delimited string. This means that key/tag names should not use spaces. If that's a requirement, then use arrays only.
Install
npm i @haxtra/memory-cache
Create
const Cache = require('@haxtra/memory-cache')
const cache = new Cache({
state: {},
gc: 600,
logger: null,
})
Set / Update
cache.set(key, item)
cache.set(key, item, {
expireIn: false,
expireAt: false,
tags: false
})
Get
cache.get(key)
cache.get(key, {
default: null,
maxAge: false,
force: false,
})
cache.getMeta(key)
Delete
cache.delete(str|arr)
cache.clear()
Tags
Note: .getTagged
does not check for expiration. If you require fresh items only, run .deleteExpired
first.
cache.getTagged(str|arr)
cache.getTagged(str|arr, {
all: false,
meta: false,
})
Delete tagged
cache.deleteTagged(str|arr)
cache.deleteTagged(str|arr, {all:true})
Events
Events are conceptual, they are just tags. Tags should describe the data, while events should describe action, upon which the item is invalidated. Tags and events can be set using tags
option on .set
, and the convention is to prefix event names with on.
ie. on.update
.
A semantic function is provided to be used with events, and it's equal to .deleteTagged
.
cache.trigger(str|arr)
cache.trigger(str|arr, {all:true})
Info
cache.keys(validOnly?)
cache.count(validOnly?)
cache.tags(validOnly?)
Garbage Collection
Manual
cache.deleteExpired()
Auto
Runs periodically to clear expired items. Must be started manually.
cache.gcStart()
cache.gcStop()
cache.gcStatus()
Instances
const newCache = cache.spawn(opts?)
cache.dispose()
Export / Import
Cache state can be exported and restored later on.
cache.export()
cache.export({persistent:true})
cache.export({expired:true})
cache.export({object:true})
Import
cache.import(json|object)
Logger
memory-cache
will log its events if logger is attached.
const cache = new Cache({logger:console.log})
cache.logger = console.log
Haxxor
cache.$
License
MIT