Skip to content

Commit

Permalink
fix(batch-delegate): memoize the key arguments correctly (#396)
Browse files Browse the repository at this point in the history
  • Loading branch information
ardatan authored Jan 2, 2025
1 parent c60a8f4 commit da65b2d
Show file tree
Hide file tree
Showing 5 changed files with 422 additions and 19 deletions.
65 changes: 65 additions & 0 deletions .changeset/wicked-islands-march.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
---
'@graphql-tools/batch-delegate': patch
---

Memoize the key arguments correctly;

With the following schema and resolvers, `userById` should batch all the requests to `usersByIds`;

```ts
{
typeDefs: /* GraphQL */ `
type User {
id: ID!
email: String!
}
type Query {
userById(id: ID!): User
usersByIds(ids: [ID!]): [User]
}
`,
resolvers: {
Query: {
usersByIds: (_root, args) => {
return args.ids.map((id: string) => users.find((user) => user.id === id));
},
userById: (root, args, context, info) => {
return batchDelegateToSchema({
schema: userSubschema,
fieldName: 'usersByIds',
key: args.id,
rootValue: root,
context,
info,
})
},
},
},
}
```

This query should batch all the requests to `usersByIds`:

```graphql
{
userById(id: "1") {
id
email
}
userById(id: "2") {
id
email
}
}
```

The delegation request should be;

```graphql
{
usersByIds(ids: ["1", "2"]) {
id
email
}
}
```
4 changes: 2 additions & 2 deletions packages/batch-delegate/src/batchDelegateToSchema.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { getLoader } from './getLoader.js';
import { BatchDelegateOptions } from './types.js';

export function batchDelegateToSchema<TContext = any>(
options: BatchDelegateOptions<TContext>,
export function batchDelegateToSchema<TContext = any, K = any, V = any, C = K>(
options: BatchDelegateOptions<TContext, K, V, C>,
): any {
const key = options.key;
if (key == null) {
Expand Down
13 changes: 10 additions & 3 deletions packages/batch-delegate/src/getLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ import DataLoader from 'dataloader';
import { getNamedType, GraphQLList, GraphQLSchema, print } from 'graphql';
import { BatchDelegateOptions } from './types.js';

const DEFAULT_ARGS_FROM_KEYS = (keys: ReadonlyArray<any>) => ({ ids: keys });

function createBatchFn<K = any>(options: BatchDelegateOptions) {
const argsFromKeys =
options.argsFromKeys ?? ((keys: ReadonlyArray<K>) => ({ ids: keys }));
const argsFromKeys = options.argsFromKeys ?? DEFAULT_ARGS_FROM_KEYS;
const fieldName = options.fieldName ?? options.info.fieldName;
const { valuesFromResults, lazyOptionsFn } = options;

Expand Down Expand Up @@ -103,6 +104,8 @@ export function getLoader<K = any, V = any, C = K>(
fieldNodes = info.fieldNodes[0] && getActualFieldNodes(info.fieldNodes[0]),
selectionSet = fieldNodes?.[0]?.selectionSet,
returnType = info.returnType,
argsFromKeys = DEFAULT_ARGS_FROM_KEYS,
key,
} = options;
const loaders = getLoadersMap<K, V, C>(context ?? GLOBAL_CONTEXT, schema);

Expand All @@ -119,7 +122,11 @@ export function getLoader<K = any, V = any, C = K>(

const fieldNode = fieldNodes?.[0];
if (fieldNode?.arguments) {
cacheKey += fieldNode.arguments.map((arg) => memoizedPrint(arg)).join(',');
const args = argsFromKeys([key]);
cacheKey += fieldNode.arguments
.filter((arg) => arg.name.value in args)
.map((arg) => memoizedPrint(arg))
.join(',');
}

let loader = loaders.get(cacheKey);
Expand Down
2 changes: 0 additions & 2 deletions packages/batch-delegate/tests/basic.example.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ describe('batch delegation within basic stitching example', () => {
const chirps: any = result.data!['trendingChirps'];
expect(chirps[0].chirpedAtUser.email).not.toBe(null);
});

test('works with key arrays', async () => {
let numCalls = 0;

Expand Down Expand Up @@ -216,7 +215,6 @@ describe('batch delegation within basic stitching example', () => {
],
});
});

test('works with keys passed to lazyOptionsFn', async () => {
let numCalls = 0;

Expand Down
Loading

0 comments on commit da65b2d

Please sign in to comment.