Skip to content

TypeScript-based caching decorator (currently supports Redis and NodeCache)

License

Notifications You must be signed in to change notification settings

JohanWillfred/type-cacheable

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build Status

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:

import * as Redis from 'redis';
import { useRedisAdapter } from 'type-cacheable';

const client = Redis.createClient();
useRedisAdapter(client);

To use the ioredis adapter, add the following code to your entry point:

import * as IoRedis from 'ioredis';
import { useIoRedisAdapter } from 'type-cacheable';

const client = new IoRedis();
useIoRedisAdapter(client);

To use the node-cache adapter, add the following code to your entry point:

import * as NodeCache from 'node-cache';
import { useNodeCacheAdapter } from 'type-cacheable';

const client = new NodeCache.default();
useNodeCacheAdapter(client);

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 above
client.setOptions(<CacheManagerOptions>{
  excludeContext: false, // Defaults to true. If you don't pass a specific hashKey into the decorators, one will be generated by serializing the arguments passed in and optionally the context of the instance the method is being called on.
  ttlSeconds: 0, // A global setting for the number of seconds the decorated method's results will be cached for.
});

Currently, there are two decorators available in this library: @Cacheable and @CacheClear. Here is a sample of how they can be used:

import * as Redis from 'redis';
import { Cacheable, CacheClear } from 'type-cacheable';

const userClient = Redis.createClient();

class TestClass {
  public aProp: string = 'aVal!';

  private userRepository: Repository<User>;

  // This static method is being called to generate a cache key based on the given arguments.
  // Not featured here: the second argument, context, which is the instance the method
  // was called on.
  static setCacheKey = (args: any[]) => args[0];

  // If getUserById('123') were called, the return value would be cached
  // in a hash under user:123, which would expire in 86400 seconds
  @Cacheable({ cacheKey: TestClass.setCacheKey, hashKey: 'user', client: userClient, ttl: 86400 })
  public async getUserById(id: string): Promise<any> {
    return this.userRepository.findOne(id);
  }

  // If getProp('123') were called, the return value would be cached
  // under 123 in this case for 10 seconds
  @Cacheable({ cacheKey: TestClass.setCacheKey, ttl: args => args[1] })
  public async getProp(id: string, cacheForSeconds: number): Promise<any> {
    return this.aProp;
  }

  // If setProp('123', 'newVal') were called, the value cached under
  // key 123 would be deleted in this case.
  @CacheClear({ cacheKey: TestClass.setCacheKey })
  public async setProp(id: string, value: string): Promise<void> {
    this.aProp = value;
  }
}

@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:

interface CacheOptions {
  cacheKey?: string | CacheKeyBuilder; // Individual key the result of the decorated method should be stored on
  hashKey?: string | CacheKeyBuilder; // Set name the result of the decorated method should be stored on (for hashes)
  client?: CacheClient; // If you would prefer use a different cache client than passed into the adapter, set that here
  noop?: boolean; // Allows for consuming libraries to conditionally disable caching. Set this to true to disable caching for some reason.
  ttlSeconds?: number | TTLBuilder; // Number of seconds the cached key should live for
}

@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:

interface CacheClearOptions {
  cacheKey?: string | CacheKeyBuilder; // Individual key the result of the decorated method should be stored on
  hashKey?: string | CacheKeyBuilder; // Set name the result of the decorated method should be stored on (for hashes)
  client?: CacheClient; // If you would prefer use a different cache client than passed into the adapter, set that here
  noop?: boolean; // Allows for consuming libraries to conditionally disable caching. Set this to true to disable caching for some reason.
  isPattern?: boolean; // Will remove pattern matched keys from cache (ie: a 'foo' cacheKey will remove ['foolish', 'foo-bar'] matched keys assuming they exist)
}
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.

TypeScript Configuration

{
  "target": "es2015", // at least
  "experimentalDecorators": true
}

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.

About

TypeScript-based caching decorator (currently supports Redis and NodeCache)

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 100.0%