Giter Site home page Giter Site logo

darraghoriordan / type-cacheable Goto Github PK

View Code? Open in Web Editor NEW

This project forked from joshuaslate/type-cacheable

0.0 2.0 0.0 608 KB

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

License: MIT License

TypeScript 100.00%

type-cacheable's Introduction

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.

type-cacheable's People

Contributors

joshuaslate avatar dependabot-preview[bot] avatar dvarnai avatar lbayas avatar dependabot[bot] avatar olehcambel avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.