Skip to content
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
10 changes: 9 additions & 1 deletion packages/plugins/typescript/operations/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export const plugin: PluginFunction<
// For Fragment types to resolve correctly, we must get read all docs (`standard` and `external`)
// Fragment types are usually (but not always) in `external` files in certain setup, like a monorepo.
const allDocumentsAST = concatAST(parsedDocuments.all.documentNodes);
const fragmentNames = new Set<string>();
const allFragments: LoadedFragment[] = [
...(
allDocumentsAST.definitions.filter(
Expand All @@ -69,7 +70,14 @@ export const plugin: PluginFunction<
isExternal: false,
})),
...(config.externalFragments || []),
];
].filter(fragment => {
if (fragmentNames.has(fragment.name)) {
return false;
}

fragmentNames.add(fragment.name);
return true;
});

const visitor = new TypeScriptDocumentsVisitor(schema, config, allFragments);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { buildSchema, parse } from 'graphql';
import { beforeEach, vi } from 'vitest';

const { visitorSpy } = vi.hoisted(() => ({
visitorSpy: [] as unknown[][],
}));

vi.mock('../src/visitor.js', () => ({
TypeScriptDocumentsVisitor: class MockTypeScriptDocumentsVisitor {
config = { noExport: false };

constructor(...args: unknown[]) {
visitorSpy.push(args);
}

getImports() {
return [];
}

getGlobalDeclarations() {
return [];
}
},
}));

describe('TypeScript Operations Plugin - externalFragments', () => {
beforeEach(() => {
visitorSpy.length = 0;
});

it('dedupes repeated external fragments before visiting documents', async () => {
const { plugin } = await import('../src/index.js');

const schema = buildSchema(/* GraphQL */ `
type Query {
user: User
}

type User {
id: ID!
name: String!
}
`);

const query = parse(/* GraphQL */ `
query User {
user {
...UserFragment
}
}
`);

const externalFragment = {
node: parse(/* GraphQL */ `
fragment UserFragment on User {
id
name
}
`).definitions[0],
name: 'UserFragment',
onType: 'User',
isExternal: true,
};

await plugin(
schema,
[{ location: '', document: query }],
{
externalFragments: [externalFragment, externalFragment],
},
{ outputFile: '' },
);

const fragments = visitorSpy[0][2];

expect(fragments).toHaveLength(1);
expect(fragments[0].name).toBe('UserFragment');
});
});
Loading