cache#
Database-backed cache for Node.js.
Requirements#
A MongoDB-compatible database. Pass an existing database, as a NodeDK scaffold plugin does.
Install#
npm i @nodedk/cache
Usage#
var createCache = require('@nodedk/cache')
module.exports = async function example(db) {
var cache = createCache({ db, expires: 3600 })
await cache.set('user:1', { name: 'Ada' })
return cache.get('user:1')
}
createCache({ db, expires, collection = 'cache' }) returns the cache synchronously. db is required; expires is the optional default lifetime in seconds. Without it, values do not expire by default.
Cache keys are stored as document _id values and use the database's built-in
unique _id index.
Set expires to define a default lifetime in seconds:
var cache = createCache({
db,
expires: 3600
})
Use collection to override the default cache collection name:
var cache = createCache({
db,
collection: 'application-cache'
})
API#
cache.set(id, value, options = {})#
Stores a value under id and resolves to that value. A falsy ID resolves to null. options.expires accepts an absolute Date, or 0 to disable expiration for this value. All cache methods return promises.
await cache.set('user:1', {
name: 'Ada'
})
Override the default expiration with a date:
var expires = new Date(Date.now() + 5 * 60 * 1000)
await cache.set('user:1', { name: 'Ada' }, { expires })
Set expires to 0 to store a value without expiration:
await cache.set('user:1', { name: 'Ada' }, { expires: 0 })
cache.get(id)#
var user = await cache.get('user:1')
get returns null when the key does not exist or has expired. Expired entries
are removed when read.
Delete a value#
Set a value to null to delete it. The deleted value is returned, or null if
the key did not exist.
var deleted = await cache.set('user:1', null)
cache.clear()#
var result = await cache.clear()
console.log(result.n)
clear returns the number of deleted entries as { n }.
cache.sweep()#
var result = await cache.sweep()
console.log(result.n)
sweep deletes all expired entries and returns the number deleted as { n }.
Created by Vidar Eldøy