@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
| Method | Description |
|---|---|
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
| Option | Type | Default | Description |
|---|---|---|---|
batch | boolean | true | Enable request batching |
maxBatchSize | number | Infinity | Max keys per batch |
cache | boolean | true | Enable promise caching |
cacheKeyFn | (key) => CacheKey | identity | Map key to cache key |
cacheMap | MapLike | new Map() | Custom cache implementation |
scheduler | (fn) => void | process.nextTick | Controls 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
| Method | Returns | Description |
|---|---|---|
load(key) | Promise<Value> | Single key; auto-batched within same tick |
loadMany(keys) | Promise<(Value|Error)[]> | Multiple keys |
clear(key) | this | Remove single cache entry |
clearAll() | this | Clear entire cache |
prime(key, value) | this | Pre-populate cache |
Options
| Option | Type | Default |
|---|---|---|
batch | boolean | true |
maxBatchSize | number | Infinity |
cache | boolean | true |
cacheKeyFn | (key) => CacheKey | identity |
cacheMap | MapLike | new Map() |
scheduler | (fn) => void | process.nextTick |