Skip to content

Commit baf07db

Browse files
shimeezleebyron
authored andcommitted
Adding maxBatchSize to options (#42)
1 parent 0547398 commit baf07db

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,9 @@ Create a new `DataLoader` given a batch loading function and options.
160160
- *batch*: Default `true`. Set to `false` to disable batching, instead
161161
immediately invoking `batchLoadFn` with a single load key.
162162

163+
- *maxBatchSize*: Default infinite. Limits the number of items that get
164+
passed in to the `batchLoadFn`.
165+
163166
- *cache*: Default `true`. Set to `false` to disable caching, instead
164167
creating a new Promise and new key in the `batchLoadFn` for every load.
165168

src/__tests__/dataloader-test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,22 @@ describe('Primary API', () => {
6262
expect(loadCalls).to.deep.equal([ [ 1, 2 ] ]);
6363
});
6464

65+
it('batches multiple requests with max batch sizes', async () => {
66+
var [ identityLoader, loadCalls ] = idLoader({ maxBatchSize: 2 });
67+
68+
var promise1 = identityLoader.load(1);
69+
var promise2 = identityLoader.load(2);
70+
var promise3 = identityLoader.load(3);
71+
72+
var [ value1, value2, value3 ] =
73+
await Promise.all([ promise1, promise2, promise3 ]);
74+
expect(value1).to.equal(1);
75+
expect(value2).to.equal(2);
76+
expect(value3).to.equal(3);
77+
78+
expect(loadCalls).to.deep.equal([ [ 1, 2 ], [ 3 ] ]);
79+
});
80+
6581
it('coalesces identical requests', async () => {
6682
var [ identityLoader, loadCalls ] = idLoader();
6783

src/index.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ type Options<K, V> = {
1919
cache?: boolean;
2020
cacheKeyFn?: (key: any) => any;
2121
cacheMap?: CacheMap<K, Promise<V>>;
22+
maxBatchSize?: number;
2223
};
2324

2425
// If a custom cache is provided, it must be of this type (a subset of ES6 Map).
@@ -221,6 +222,14 @@ function dispatchQueue<K, V>(loader: DataLoader<K, V>) {
221222
var queue = loader._queue;
222223
loader._queue = [];
223224

225+
var maxBatchSize = loader._options && loader._options.maxBatchSize ||
226+
queue.length;
227+
for (var i = 0; i < queue.length / maxBatchSize; i++) {
228+
loadKeys(loader, queue.slice(i * maxBatchSize, (i + 1) * maxBatchSize));
229+
}
230+
}
231+
232+
function loadKeys<K, V>(loader: DataLoader<K, V>, queue: LoaderQueue<K, V>) {
224233
// Collect all keys to be loaded in this dispatch
225234
var keys = queue.map(({ key }) => key);
226235

0 commit comments

Comments
 (0)