6.0.2 • Published 2 years ago

@boredland/node-ts-cache v6.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

@boredland/node-ts-cache

CI The MIT License Coverage Status

Simple and extensible caching module supporting decorators.

Install

yarn add @boredland/node-ts-cache

Note: The underlying storage layer must be installed separately.

Storage

StorageInstall
memoryyarn add @boredland/node-ts-cache-storage-memory
node-fsyarn add @boredland/node-ts-cache-storage-node-fs
ioredisyarn add @boredland/node-ts-cache-storage-ioredis
postgresyarn add @boredland/node-ts-cache-storage-pg
elasticsearchyarn add @boredland/node-ts-cache-storage-elasticsearch

Usage

withCacheFactory

Function wrapper factory for arbitrary functions. The cache key is caculated based on the parameters passed to the function.

import { withCacheFactory, CacheContainer } from '@boredland/node-ts-cache'
import { MemoryStorage } from '@boredland/node-ts-cache-storage-memory'

const doThingsCache = new CacheContainer(new MemoryStorage())

const someFn = (input: { a: string, b: number })

const wrappedFn = withCacheFactory(doThingsCache)(someFn);

const result = someFn({ a: "lala", b: 123 })

With decorator

Caches function response using the given options. By default, uses all arguments to build an unique key.

Note: @Cache will consider the return type of the function. If the return type is a thenable, it will stay that way, otherwise not.

import { Cache, CacheContainer } from '@boredland/node-ts-cache'
import { MemoryStorage } from '@boredland/node-ts-cache-storage-memory'

const userCache = new CacheContainer(new MemoryStorage())

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

Direct usage

import { CacheContainer } from '@boredland/node-ts-cache'
import { MemoryStorage } from '@boredland/node-ts-cache-storage-memory'

const myCache = new CacheContainer(new MemoryStorage())

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

        if (cachedUsers) {
            return cachedUsers
        }

        const newUsers = ["Max", "User"]

        await myCache.setItem("users", newUsers, {ttl: 60})

        return newUsers
    }
}

Logging

This project uses debug to log useful caching information. Set environment variable DEBUG=node-ts-cache to enable logging.

Development & Testing

This project follows the monorepo architecture using yarn workspaces.

To start development and run tests for all the packages, run:

cd node-ts-cache
yarn
yarn build
yarn test