Class Cache<TType>

Cache class can be derived from any ICacheAdapter.

import { Cache, MemoryCacheAdapter } from "@daiso-tech/core";

const cache = new Cache(new MemoryCacheAdapter());

Type Parameters

  • TType = unknown

Implements

Constructors

Methods

  • The add method adds a key with given value when key doesn't exists. Returns true when key doesn't exists otherwise false will be returned. You can provide a ttl value. If null is passed, the item will not expire.

    Parameters

    Returns LazyPromise<boolean>

  • The decrement method will decrement the given key if found otherwise nonthing will occur. Returns true if key exists otherwise false will be returned. An error will thrown if the key is not a number.

    Parameters

    • key: string
    • value: Extract<TType, number> = ...

    Returns LazyPromise<boolean>

    TypeCacheError An error will thrown if the key is not a number.

  • The getGroup method returns the group name.

    Returns string

    import type { ICache } from "@daiso-tech/core";

    async function main(cache: ICache) {
    // Will be "@global"
    console.log(cache.getGroup())

    const cacheA = cache.withGroup("a");

    // Will be "@global/a"
    console.log(cacheA.getGroup())
    }
  • The increment method will increment the given key if found otherwise nonthing will occur. Returns true if key is incremented otherwise false will be returned. An error will thrown if the key is not a number.

    Parameters

    • key: string
    • value: Extract<TType, number> = ...

    Returns LazyPromise<boolean>

  • The put method replaces a key if the key exists including the ttl value or adds key that do not exists with a given ttl. Returns true if the key where replaced otherwise false is returned. You must provide a ttl value. If null is passed, the item will not expire.

    Parameters

    Returns LazyPromise<boolean>

  • The withGroup method returns a new ICache instance that groups keys together. Only keys in the group can be updated, removed, or retrieved, leaving keys outside the group unaffected. This useful for multitennat applications.

    Parameters

    Returns ICache<TType>

    import { type ICache } from "@daiso-tech/core";

    async function main(cache: ICache): Promise<void> {
    const cacheA = cache.withGroup("a");
    await cacheA.add("a", 1);

    const cacheB = cache.withGroup("b");
    await cacheB.add("b", 2);

    // Will print { a: 1, b: null }
    console.log(await cacheA.getMany(["a", "b"]));
    }