type-cacheable
TypeScript-based caching decorator to assist with caching (and clearing cache for) async methods. Currently supports Redis (redis
, ioredis
) and node-cache.
Usage
Installation
npm install --save type-cacheable
or
yarn add type-cacheable
Setup Adapter
You will need to set up the appropriate adapter for your cache. So far, there is only support for Redis (redis
, ioredis
) and node-cache
. If you would like to see more adapters added, please open an issue or, better yet, a pull request with an implementation.
To use the Redis adapter, add the following code to your entry point:
;; ;useRedisAdapterclient;
To use the ioredis adapter, add the following code to your entry point:
;; ;useIoRedisAdapterclient;
To use the node-cache adapter, add the following code to your entry point:
;; ;useNodeCacheAdapterclient;
Change Global Options
Some options can be configured globally for all decorated methods. Here is an example of how you can change these options:
// Import and set adapter as aboveclient.setOptionsCacheManagerOptions;
Currently, there are two decorators available in this library: @Cacheable
and @CacheClear
. Here is a sample of how they can be used:
;; ;
@Cacheable
The @Cacheable
decorator first checks for the given key(s) in cache. If a value is available (and not expired), it will be returned. If no value is available, the decorated method will run, and the cache will be set with the return value of that method. It takes CacheOptions
for an argument. The available options are:
@CacheClear
The @CacheClear
decorator first runs the decorated method. If that method does not throw, @CacheClear
will delete the given key(s) in the cache. It takes CacheClearOptions
for an argument. The available options are:
CacheKeyBuilder
CacheKeyBuilder
can be passed in as the value for cacheKey or hashKey on either @Cacheable
or @CacheClear
. This is a function that is passed two arguments, args
and context
, where args
is the arguments the decorated method was called with, and context
is the object (this
value) the method was called on. This function must return a string.
For example, if you would like to cache a user, you might want to cache them by id. Refer to the sample above to see how this could be done.
Note
If no cacheKey is passed in, one will be generated by serializing and hashing the method name, arguments, and context in which the method was called. This will not allow you to reliably clear caches, but is available as a convenience.
Using Adapter directly
It can happen that you need to read/write data from cache directly, without decorators.
To achieve this you can use cacheManager
. For example:
;;
TypeScript Configuration
Contribution
Feel free to contribute by forking this repository, making, testing, and building your changes, then opening a pull request. Please try to maintain a uniform code style.