Simple and extensible caching module supporting decorators.
yarn add @ioki/node-ts-cache
Note: The underlying storage layer must be installed separately.
Storage | Install |
---|---|
memory | yarn add @ioki/node-ts-cache-storage-memory |
node-fs | yarn add @ioki/node-ts-cache-storage-node-fs |
ioredis | yarn add @ioki/node-ts-cache-storage-ioredis |
postgres | yarn add @ioki/node-ts-cache-storage-pg |
elasticsearch | yarn add @ioki/node-ts-cache-storage-elasticsearch |
Function wrapper factory for arbitrary functions. The cache key is caculated based on the parameters passed to the function.
import { withCacheFactory, CacheContainer } from '@ioki/node-ts-cache'
import { MemoryStorage } from '@ioki/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 })
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 '@ioki/node-ts-cache'
import { MemoryStorage } from '@ioki/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"]
}
}
import { CacheContainer } from '@ioki/node-ts-cache'
import { MemoryStorage } from '@ioki/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
}
}
This project uses debug to log useful caching information. Set environment variable DEBUG=node-ts-cache to enable logging.
Just use the memory storage adapter in your tests.
Distributed under the MIT License. See LICENSE.md for more information.
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
We're using changeset to automate the release process. The only thing to be done is to commit a changeset.
As this is a fork of the original node-ts-cache, all credit goes to the upstream project by havsar.
Structural changes have been made by boredland in order to align more with our use-case.
- join us @ioki and make this one of your projects
- create issues and pull requests, we're happy to enhance this
ioki Mobility - @ioki_mobility
Project Link: https://github.com/ioki-mobility/node-ts-cache