Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use batchLoadFn.apply instead of directly invoking batchLoadFn #182

Merged
merged 2 commits into from Nov 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 14 additions & 2 deletions README.md
Expand Up @@ -90,7 +90,19 @@ minimal outgoing data requests.
#### Batch Function

A batch loading function accepts an Array of keys, and returns a Promise which
resolves to an Array of values. There are a few constraints that must be upheld:
resolves to an Array of values or Error instances. The loader itself is provided
as the `this` context.

```js
async function batchFunction(keys) {
const results = await db.fetchAllKeys(keys)
return keys.map(key => results[key] || new Error(`No result for ${key}`))
}

const loader = new DataLoader(batchFunction)
```

There are a few constraints this function must uphold:

* The Array of values must be the same length as the Array of keys.
* Each index in the Array of values must correspond to the same index in the Array of keys.
Expand All @@ -116,7 +128,7 @@ with the original keys `[ 2, 9, 6, 1 ]`:
[
{ id: 2, name: 'San Francisco' },
{ id: 9, name: 'Chicago' },
null,
null, // or perhaps `new Error()`
{ id: 1, name: 'New York' }
]
```
Expand Down
13 changes: 13 additions & 0 deletions src/__tests__/dataloader.test.js
Expand Up @@ -30,6 +30,19 @@ describe('Primary API', () => {
expect(value1).toBe(1);
});

it('references the loader as "this" in the batch function', async () => {
let that;
const loader = new DataLoader(async function (keys) {
that = this;
return keys;
});

// Trigger the batch function
await loader.load(1);

expect(that).toBe(loader);
});

it('supports loading multiple keys in one call', async () => {
const identityLoader = new DataLoader(keys => Promise.resolve(keys));

Expand Down
3 changes: 2 additions & 1 deletion src/index.js
Expand Up @@ -253,7 +253,8 @@ function dispatchQueueBatch<K, V>(

// Call the provided batchLoadFn for this loader with the loader queue's keys.
var batchLoadFn = loader._batchLoadFn;
var batchPromise = batchLoadFn(keys);
// Call with the loader as the `this` context.
var batchPromise = batchLoadFn.call(loader, keys);

// Assert the expected response from batchLoadFn
if (!batchPromise || typeof batchPromise.then !== 'function') {
Expand Down