Class CachedHandler<TIn, TOut>

Caches output data from the source handler based on the input object. The fields parameter can be used to instead use one or more specific entries from the input object as cache key, so has as actual required typing (keyof TIn)[].

A WeakMap is used internally so strict object equality determines cache hits, and data will be removed once the key stops existing. This also means that the cache key needs to be an object. Errors will be thrown in case a primitive is used.

Type Parameters

  • TIn extends Record<string, any>

  • TOut = void

Hierarchy

Constructors

Properties

cache: WeakMap<object, NestedMap<TOut>>
fields?: [keyof TIn, ...(keyof TIn)[]]
source: AsyncHandler<TIn, TOut>

Methods

  • Checks if the input can be handled by this class. If it cannot handle the input, rejects with an error explaining why.

    Parameters

    • input: TIn

      Input that could potentially be handled.

    Returns Promise<void>

    A promise resolving if the input can be handled, rejecting with an Error if not.

  • Returns the WeakMap that contains actual objects that were cached, so the last WeakMap in the chain of maps.

    Returns undefined if no such map exists because earlier keys were not cached.

    Will always return a map if ensure is set to true, in such a case the intermediate maps will be created and added to the previous map.

    Parameters

    • input: TIn
    • keys: object[]
    • cache: WeakMap<object, NestedMap<TOut>>
    • ensure: boolean = false

    Returns undefined | WeakMap<object, TOut>

  • Extracts the values that will be used as keys from the input object. In case the fields value was undefined, this will return an array containing the input object itself.

    Parameters

    • input: TIn

    Returns [object, ...object[]]

  • Handles the given input. This may only be called if canHandle did not reject. When unconditionally calling both in sequence, consider handleSafe instead.

    Parameters

    • input: TIn

      Input that needs to be handled.

    Returns Promise<TOut>

    A promise resolving when handling is finished.

  • Helper function that first runs canHandle followed by handle. Throws the error of canHandle if the data cannot be handled, or returns the result of handle otherwise.

    Parameters

    • input: TIn

      Input data that will be handled if it can be handled.

    Returns Promise<TOut>

    A promise resolving if the input can be handled, rejecting with an Error if not.