Documentation
    Preparing search index...

    Class DataLoader<K, V, C>

    A DataLoader creates a public API for loading data from a particular data back-end with unique keys such as the id column of a SQL table or document name in a MongoDB database, given a batch loading function.

    Each DataLoader instance contains a unique memoized cache. Use caution when used in long-lived applications or those which serve many users with different access permissions and consider creating a new instance per web request.

    Type Parameters

    • K
    • V
    • C = K
    Index

    Constructors

    Properties

    _batch: null | Batch<K, V>
    _batchLoadFn: BatchLoadFn<K, V>
    _batchScheduleFn: (cb: () => void) => void
    _cacheKeyFn: (key: K) => C
    _cacheMap: null | CacheMap<C, Promise<V>>
    _maxBatchSize: number
    name: null | string

    The name given to this DataLoader instance. Useful for APM tools.

    Is null if not set in the constructor.

    Methods

    • Clears the value at key from the cache, if it exists. Returns itself for method chaining.

      Parameters

      • key: K

      Returns this

    • Clears the entire cache. To be used when some event results in unknown invalidations across this particular DataLoader. Returns itself for method chaining.

      Returns this

    • Loads a key, returning a Promise for the value represented by that key.

      Parameters

      • key: K

      Returns Promise<V>

    • Loads multiple keys, promising an array of values:

      var [ a, b ] = await myLoader.loadMany([ 'a', 'b' ]);
      

      This is similar to the more verbose:

      var [ a, b ] = await Promise.all([
        myLoader.load('a'),
        myLoader.load('b')
      ]);
      

      However it is different in the case where any load fails. Where Promise.all() would reject, loadMany() always resolves, however each result is either a value or an Error instance.

      var [ a, b, c ] = await myLoader.loadMany([ 'a', 'b', 'badkey' ]);
      // c instanceof Error
      

      Parameters

      • keys: readonly K[]

      Returns Promise<(V | Error)[]>

    • Adds the provided key and value to the cache. If the key already exists, no change is made. Returns itself for method chaining.

      To prime the cache with an error at a key, provide an Error instance.

      Parameters

      • key: K
      • value: V | Promise<V> | Error

      Returns this