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

fix: batch delegation collapses two requests with different arguments into a single memoized loader #5189

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions packages/batch-delegate/src/getLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,17 @@ export function getLoader<K = any, V = any, C = K>(options: BatchDelegateOptions
fieldName = info.fieldName,
dataLoaderOptions,
fieldNodes = info.fieldNodes,
selectionSet = fieldNodes[0].selectionSet,
} = options;
const loaders = getLoadersMap<K, V, C>(context ?? GLOBAL_CONTEXT, schema);

let cacheKey = fieldName;

if (selectionSet != null) {
cacheKey += memoizedPrint(selectionSet);
if (fieldNodes[0]) {
const fieldNode = {
...fieldNodes[0],
alias: undefined,
};
cacheKey += memoizedPrint(fieldNode);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This breaks print memoization.

Copy link
Contributor Author

@maxbol maxbol Apr 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, sorry. Would an acceptable alternative be:

if (fieldNode.selectionSet !== undefined) {
  cacheKey += memoizedPrint(fieldNode.selectionSet);
}

if (fieldNode.arguments !== undefined) {
  cacheKey += fieldNode.arguments.map((arg) => memoizedPrint(arg)).join(",");
}

}

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

test('uses a single call even when delegating the same field multiple times', async () => {
let numCalls = 0;

const chirpSchema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
type Chirp {
chirpedAtUserId: ID!
}

type Query {
trendingChirps: [Chirp]
}
`,
resolvers: {
Query: {
trendingChirps: () => [{ chirpedAtUserId: 1 }, { chirpedAtUserId: 2 }],
},
},
});

// Mocked author schema
const authorSchema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
type User {
email: String
}

type Query {
usersByIds(ids: [ID!]): [User]
}
`,
resolvers: {
Query: {
usersByIds: (_root, args) => {
numCalls++;
return args.ids.map((id: string) => ({ email: `${id}@test.com` }));
},
},
},
});

const linkTypeDefs = /* GraphQL */ `
extend type Chirp {
chirpedAtUser: User
}
`;

const stitchedSchema = stitchSchemas({
subschemas: [chirpSchema, authorSchema],
typeDefs: linkTypeDefs,
resolvers: {
Chirp: {
chirpedAtUser: {
selectionSet: `{ chirpedAtUserId }`,
resolve(chirp, _args, context, info) {
return batchDelegateToSchema({
schema: authorSchema,
operation: 'query' as OperationTypeNode,
fieldName: 'usersByIds',
key: chirp.chirpedAtUserId,
argsFromKeys: ids => ({ ids }),
context,
info,
});
},
},
},
},
});

const query = /* GraphQL */ `
query {
trendingChirps {
chirp1: chirpedAtUser {
email
}
chirp2: chirpedAtUser {
email
}
}
}
`;

await execute({ schema: stitchedSchema, document: parse(query) });

expect(numCalls).toEqual(1);
});

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

Expand Down
107 changes: 107 additions & 0 deletions packages/batch-delegate/tests/cacheByArguments.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { execute, isIncrementalResult } from '@graphql-tools/executor';
import { OperationTypeNode, parse } from 'graphql';

import { makeExecutableSchema } from '@graphql-tools/schema';
import { batchDelegateToSchema } from '@graphql-tools/batch-delegate';
import { stitchSchemas } from '@graphql-tools/stitch';

describe('non-key arguments are taken into account when memoizing result', () => {
test('memoizes non-key arguments as part of batch delegation', async () => {
let numCalls = 0;

const chirpSchema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
type Chirp {
chirpedAtUserId: ID!
}

type Query {
trendingChirps: [Chirp]
}
`,
resolvers: {
Query: {
trendingChirps: () => [{ chirpedAtUserId: 1 }, { chirpedAtUserId: 2 }],
},
},
});

// Mocked author schema
const authorSchema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
type User {
email: String!
}

type Query {
usersByIds(ids: [ID!], obfuscateEmail: Boolean!): [User]
}
`,
resolvers: {
Query: {
usersByIds: (_root, args) => {
numCalls++;
return args.ids.map((id: string) => ({ email: args.obfuscateEmail ? '***' : `${id}@test.com` }));
},
},
},
});

const linkTypeDefs = /* GraphQL */ `
extend type Chirp {
chirpedAtUser(obfuscateEmail: Boolean!): User
}
`;

const stitchedSchema = stitchSchemas({
subschemas: [chirpSchema, authorSchema],
typeDefs: linkTypeDefs,
resolvers: {
Chirp: {
chirpedAtUser: {
selectionSet: `{ chirpedAtUserId }`,
resolve(chirp, args, context, info) {
return batchDelegateToSchema({
schema: authorSchema,
operation: 'query' as OperationTypeNode,
fieldName: 'usersByIds',
key: chirp.chirpedAtUserId,
argsFromKeys: ids => ({ ids, ...args }),
context,
info,
});
},
},
},
},
});

const query = /* GraphQL */ `
query {
trendingChirps {
withObfuscatedEmail: chirpedAtUser(obfuscateEmail: true) {
email
}
withoutObfuscatedEmail: chirpedAtUser(obfuscateEmail: false) {
email
}
}
}
`;

const result = await execute({ schema: stitchedSchema, document: parse(query) });

expect(numCalls).toEqual(2);

if (isIncrementalResult(result)) throw Error('result is incremental');

expect(result.errors).toBeUndefined();

const chirps: any = result.data!['trendingChirps'];
expect(chirps[0].withObfuscatedEmail.email).toBe(`***`);
expect(chirps[1].withObfuscatedEmail.email).toBe(`***`);

expect(chirps[0].withoutObfuscatedEmail.email).toBe(`[email protected]`);
expect(chirps[1].withoutObfuscatedEmail.email).toBe(`[email protected]`);
});
});