alsoicode / node-ts-cache

Simple and extensible caching module supporting decorators

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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"];
    }
}

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

MemoryStorage()

FsJsonStorage(fileName: string)

RedisStorage(host: string, port: number, password: string)

Test

npm test

About

Simple and extensible caching module supporting decorators

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

License:MIT License


Languages

Language:TypeScript 100.0%