
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Cache manager that doesn't suck.
Make the result of you async functions cacheable, automatically pickle and unpickle the data.
Manage all cache keys in one place, use a simple ._clearCache()
to purge cache.
var Redis = require('redis');
var Cacheable = require('cacheable');
var client = Redis.createClient();
var cached = Cacheable({
client: client,
ttl: 60, // set a default max age of one minute for `cached.set`
prefix: 'myapp:' // the prefix for every cache key
});
cached.set(key, value, callback)
cached.set(key, value, 300, callback)
cached.get(key, callback)
cached.del(['abc', 'aba'], callback)
Wraping an async function:
// Get remote content that expires in 3600 seconds
var getUrlContent = cached.wrap(function(url, callback) {
request(url, function() {
// ...
})
}, 'url-{0}', 3600)
Manage cache for your models:
function User(data) {
this.attributes = data
}
User.prototype.toJSON = function() {
return this.attributes
}
// get user by id
User.get = function(user_id, callback) {
// get the user from data base
// ...
var user = new User(data)
callback(err, user);
}
User.prototype.getPostIds = function(start, limit, callback) {
callback(null, [1,2,3...])
}
// register the constructor first
cached.register(User)
// enable cache for `User.get` method
// So when you call `User.get(some_id)`, it will fetch data
// from cache first, when cache not found, then the original function will be called.
User.enableCache('get', '{_model_}:{0}') // '{0}' means the `arguments[0]`
// You can also enable cache for an instance method
User.enableCache('.getPostIds', '{_model_}:posts-{0}-{1}')
You have to register
all model constructors, so when cache is hit, the cached manager would know
how to restore the data as a proper JavaScript Object.
If your model constructor doesn't have a name, you can give a name as the second parameter, then cached will use this name.
var Book = function() {
}
cached.register(Book, 'Book')
Your class.prototype must have a .toJSON
method, so the cache wrapper could know how to save it to cache.
The .toJSON
will be extended by cache.register
, the output object will always have a property __cachedname
,
as is the constructor's modelName. You can add a .toObject = .toJSON
, and use .toObject
whenever you need a clean object.
If an ._unpickle
method is also defined, it will be called each time the object is restored from cache.
That is:
var item = new User(json)
item._unpickle()
return item
Note that it would be impossible to unpickle a cache if the constructor's name was changed.
When registered, the class will have a property ._cacheKeys
and an instance would have
a method ._clearCache()
.
User.prototype.destroy = function(callback) {
var self = this
// destroy the item from database
db.destroy(..., function() {
// then clear the cache
self._clearCache(callback)
})
}
Wrap an standard nodejs async function(which should have a callback(err, result)
as the last parameter).
The ttl
is in seconds. If no ttl
set, the cache will never automatically expire, even it an options.ttl
is passed when you do new Cached()
.
The parameter key
is a pattern for formatting real cache keys.
The default key
is:
{_model_}:{_fn_}
{_fn_}
is the name of the function fn
. If not found, an error will throw.
So you'd better alway name your functions, like this:
User.get = function get(id) {
// ...
}
{_model_}
equals to {this.name}
, which is this.modelName || this.name
in the scope when the function is called.
For a class method, this usually means the name of a constructor.
Numbers like {0}
is indexes of arguments when the function is called.
%j{0}
mean the first argument value will be converted to json.
When a cls
is registered, you can use cls.enableCache
to enable cache for class/instance methods.
If methodName
starts with a dot (.)
, it will be considered as an instance method, otherwise,
it's a class method.
/**
*
* List all ids
*
* Options:
*
* `limit`: limit per page
* `offset`: offset
*
*/
User.getAllIds = function(options, callback) {
}
User.prototype.getPostIds = function(start, limit, callback) {
// get user's posts
callback(null, [1,2,3...])
}
User.enableCache('getAllIds', 'ids-{0.limit}-{0.offset}')
User.enableCache('.getPostIds', 'posts-{0}-{1}')
// You can omit the key, cacheable will automatically use the method name
User.enableCache('.getPostIds', 3600)
// KEY: '{_model_}:{id}:getTagsIds', expires in: 3600 seconds
It is strongly recommended to use this approach to add cache, instead of directly call cached.wrap
.
the MIT licence.
FAQs
High Performance Layer 1 / Layer 2 Caching with Keyv Storage
The npm package cacheable receives a total of 885,204 weekly downloads. As such, cacheable popularity was classified as popular.
We found that cacheable demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.