Coder Social home page Coder Social logo

kervoaz / node-ts-cache Goto Github PK

View Code? Open in Web Editor NEW

This project forked from havsar/node-ts-cache

0.0 1.0 0.0 103 KB

Simple and extensible caching module supporting decorators

Home Page: https://www.npmjs.com/package/node-ts-cache

License: MIT License

TypeScript 100.00%

node-ts-cache's Introduction

Travis CI David npm The MIT License

NPM

node-ts-cache

Simple and extensible caching module supporting decorators

Install

npm install --save node-ts-cache

Usage

With decorator

Caches function response using the given options. Works with different strategies and storages. Uses all arguments to build an unique key.

@Cache(strategy, options)

  • strategy: A supported caching Strategy
  • options: Options passed to the strategy for this particular method

Note: @Cache always converts the method response to a promise because caching might be async.

import { Cache, ExpirationStrategy, MemoryStorage } from "node-ts-cache";

const myStrategy = new ExpirationStrategy(new MemoryStorage());

class MyService {
    
    @Cache(myStrategy, { ttl: 60 })
    public async getUsers(): Promise<string[]> {
        return ["Max", "User"];
    }
}

Cache decorator generates cache key according to class name, class method and args (with JSON.stringify). If you want another key creation logic you can bypass key creation strategy to the Cache decorator.

import { Cache, ExpirationStrategy, MemoryStorage, IKeyStrategy } from "node-ts-cache";

class MyKeyStrategy implements IKeyStrategy {
   public getKey(className: string, methodName: string, args: any[]): Promise<string> | string {
        // Here you can implement your own way of creating cache keys
        return `foo bar baz`;
   }
}

const myStrategy = new ExpirationStrategy(new MemoryStorage());
const myKeyStrategy = new MyKeyStrategy();

class MyService {
    
    @Cache(myStrategy, { ttl: 60 }, myKeyStrategy)
    public async getUsers(): Promise<string[]> {
        return ["Max", "User"];
    }
}

Directly

import { ExpirationStrategy, MemoryStorage } from "node-ts-cache";

const myCache = new ExpirationStrategy(new MemoryStorage());

class MyService {
    
    public async getUsers(): Promise<string[]> {
        const cachedUsers = await myCache.getItem<string[]>("users");
        if (cachedUsers) {
            return cachedUsers;
        }

        const newUsers = ["Max", "User"];
        await myCache.setItem("users", newUsers, {  ttl: 60 });

        return newUsers;
    }
}

Strategies

ExpirationStrategy

Cached items expire after a given amount of time.

  • ttl: (Default: 60) Number of seconds to expire the cachte item
  • isLazy: (Default: true) If true, expired cache entries will be deleted on touch. If false, entries will be deleted after the given ttl.
  • isCachedForver: (Default: false) If true, cache entry has no expiration.

Storages

Note: For specific storages, client libraries must be installed:

Storage Needed client library
RedisStorage npm install redis

MemoryStorage()

FsJsonStorage(fileName: string)

RedisStorage(clientOpts: RedisClientOptions)

Test

npm test

node-ts-cache's People

Contributors

havsar avatar dlukanin avatar

Watchers

James Cloos 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.