Skip to main content

@winglet/data-loader

@winglet/data-loader npm versionlicense
yarn add @winglet/data-loader

Batching and caching utility for asynchronous data fetching, inspired by GraphQL DataLoader. Automatically collects individual load() calls within the same tick into a single batch request, eliminating the N+1 query problem with a built-in promise cache.

Installation

yarn add @winglet/data-loader

API

Constructor

import { DataLoader } from '@winglet/data-loader';

const loader = new DataLoader<Key, Value>(batchLoader, options?);

batchLoader receives an array of keys and must return a Promise resolving to values (or Error) in the same order.

Instance Methods

MethodDescription
load(key)Returns Promise<Value> for a single key; batches automatically
loadMany(keys)Returns Promise<(Value | Error)[]> for multiple keys
clear(key)Removes a single key from the cache
clearAll()Clears the entire cache
prime(key, value)Pre-populates the cache

Options

OptionTypeDefaultDescription
batchbooleantrueEnable request batching
maxBatchSizenumberInfinityMax keys per batch
cachebooleantrueEnable promise caching
cacheKeyFn(key) => CacheKeyidentityMap key to cache key
cacheMapMapLikenew Map()Custom cache implementation
scheduler(fn) => voidprocess.nextTickControls batching timing

Usage Examples

import { DataLoader } from '@winglet/data-loader';

const userLoader = new DataLoader<number, User>(async (ids) => {
const users = await fetchUsersByIds(ids);
return ids.map(id => users.find(u => u.id === id) ?? new Error(`Not found: ${id}`));
});

// These three calls batch into a single fetchUsersByIds([1, 2, 3])
const [alice, bob, carol] = await Promise.all([
userLoader.load(1),
userLoader.load(2),
userLoader.load(3),
]);
// Cache management
userLoader.prime(4, { id: 4, name: 'Dave' });
userLoader.clear(1);
userLoader.clearAll();
AI Agent Reference

AI Reference

Package: @winglet/data-loader v0.10.0 Purpose: Request batching and caching for async data fetching (inspired by GraphQL DataLoader).

Exports

import { DataLoader } from '@winglet/data-loader';
import type { DataLoaderOptions } from '@winglet/data-loader';

Constructor

const loader = new DataLoader<Key, Value>(batchLoadFn, options?);
// batchLoadFn: (keys: Key[]) => Promise<(Value | Error)[]>

Instance methods

MethodReturnsDescription
load(key)Promise<Value>Single key; auto-batched within same tick
loadMany(keys)Promise<(Value|Error)[]>Multiple keys
clear(key)thisRemove single cache entry
clearAll()thisClear entire cache
prime(key, value)thisPre-populate cache

Options

OptionTypeDefault
batchbooleantrue
maxBatchSizenumberInfinity
cachebooleantrue
cacheKeyFn(key) => CacheKeyidentity
cacheMapMapLikenew Map()
scheduler(fn) => voidprocess.nextTick