Skip to content

Commit c1aafc1

Browse files
committed
Add some documentation for DataLoader
1 parent 58ad2b4 commit c1aafc1

1 file changed

Lines changed: 51 additions & 1 deletion

File tree

README.md

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,13 +258,63 @@ module.exports = {
258258
};
259259
```
260260

261+
### Dataloader
262+
moleculer-apollo-server supports [DataLoader](https://github.com/graphql/dataloader) via configuration in the resolver definition.
263+
The called action must be compatible with DataLoader semantics -- that is, it must accept params with an array property and return an array of the same size,
264+
with the results in the same order as they were provided.
265+
266+
To activate DataLoader for a resolver, simply add `dataLoader: true` to the resolver's property object in the `resolvers` property of the service's `graphql` property:
267+
268+
```js
269+
settings: {
270+
graphql: {
271+
resolvers: {
272+
Post: {
273+
author: {
274+
action: "users.resolve",
275+
dataLoader: true,
276+
rootParams: {
277+
author: "id",
278+
},
279+
},
280+
voters: {
281+
action: "users.resolve",
282+
dataLoader: true,
283+
rootParams: {
284+
voters: "id",
285+
},
286+
},
287+
...
288+
```
289+
Since DataLoader only expects a single value to be loaded at a time, only one `rootParams` key/value pairing will be utilized, but `params` and GraphQL child arguments work properly.
290+
291+
You can also specify [options](https://github.com/graphql/dataloader#api) for construction of the DataLoader in the called action definition's `graphql` property. This is useful for setting things like `maxBatchSize'.
292+
293+
```js
294+
resolve: {
295+
params: {
296+
id: [{ type: "number" }, { type: "array", items: "number" }],
297+
graphql: { dataLoaderOptions: { maxBatchSize: 100 } },
298+
},
299+
handler(ctx) {
300+
this.logger.debug("resolve action called.", { params: ctx.params });
301+
if (Array.isArray(ctx.params.id)) {
302+
return _.cloneDeep(ctx.params.id.map(id => this.findByID(id)));
303+
} else {
304+
return _.cloneDeep(this.findByID(ctx.params.id));
305+
}
306+
},
307+
},
308+
```
309+
It is unlikely that setting any of the options which accept a function will work properly unless you are running moleculer in a single-node environment. This is because the functions will not serialize and be run by the moleculer-web Api Gateway.
310+
261311
## Examples
262312
263313
- [Simple](examples/simple/index.js)
264314
- `npm run dev`
265315
- [Full](examples/full/index.js)
266316
- `npm run dev full`
267-
- [Full With Dataloader](examples/full-dataloader/index.js)
317+
- [Full With Dataloader](examples/full/index.js)
268318
- set `DATALOADER` environment variable to `"true"`
269319
- `npm run dev full`
270320
# Test

0 commit comments

Comments
 (0)