Skip to content

Commit 2f7af56

Browse files
committed
Add example in documentation for converting object results to Array results.
Closes #167
1 parent 923a75f commit 2f7af56

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,23 @@ function freezeResults(batchLoader) {
502502
const myLoader = new DataLoader(freezeResults(myBatchLoader))
503503
```
504504

505+
### Batch functions which return Objects instead of Arrays
506+
507+
DataLoader expects batch functions which return an Array of the same length as
508+
the provided keys. However this is not always a common return format from other
509+
libraries. A DataLoader higher-order function can convert from one format to another. The example below converts a `{ key: value }` result to the format
510+
DataLoader expects.
511+
512+
```js
513+
function objResults(batchLoader) {
514+
return keys => batchLoader(keys).then(objValues => keys.map(
515+
key => objValues[key] || new Error(`No value for ${key}`)
516+
))
517+
}
518+
519+
const myLoader = new DataLoader(objResults(myBatchLoader))
520+
```
521+
505522

506523
## Common Back-ends
507524

0 commit comments

Comments
 (0)