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

Guard against duplicate fragment names in near-operations-file #2139

Merged
merged 1 commit into from Jul 11, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/presets/near-operation-file/src/index.ts
Expand Up @@ -102,6 +102,7 @@ export const preset: Types.OutputPreset<NearOperationFileConfig> = {
add: addPlugin,
};

const duplicateFragmentNames: string[] = [];
const fragmentNameToFile: FragmentNameToFile = options.documents.reduce((prev, documentRecord) => {
const fragments: FragmentDefinitionNode[] = documentRecord.content.definitions.filter(d => d.kind === Kind.FRAGMENT_DEFINITION) as FragmentDefinitionNode[];

Expand All @@ -110,13 +111,21 @@ export const preset: Types.OutputPreset<NearOperationFileConfig> = {
const filePath = appendExtensionToFilePath(documentRecord.filePath, extension);
const importName = baseVisitor.convertName(fragment, { suffix: 'Fragment' });

if (prev[fragment.name.value]) {
duplicateFragmentNames.push(fragment.name.value);
}

prev[fragment.name.value] = { filePath, importName, onType: fragment.typeCondition.name.value, node: fragment };
}
}

return prev;
}, {});

if (duplicateFragmentNames.length) {
throw new Error(`Multiple fragments with the name(s) "${duplicateFragmentNames.join(', ')}" were found.`);
}

const absTypesPath = resolve(baseDir, join(options.baseOutputDir, options.presetConfig.baseTypesPath));

return options.documents
Expand Down
Expand Up @@ -155,6 +155,23 @@ describe('near-operation-file preset', () => {
expect(result.map(o => o.plugins)[0]).toEqual(expect.arrayContaining([{ add: `import * as Types from '../types';\n` }]));
});

it('should fail when multiple fragments with the same name are found', () => {
expect(() =>
preset.buildGeneratesSection({
baseOutputDir: './src/',
config: {},
presetConfig: {
cwd: '/some/deep/path',
baseTypesPath: 'types.ts',
},
schema: schemaDocumentNode,
documents: [testDocuments[1], testDocuments[1]],
plugins: [{ typescript: {} }],
pluginMap: { typescript: {} as any },
})
).toThrow('Multiple fragments with the name(s) "UserFields" were found.');
});

it('Should NOT prepend the "add" plugin with Types import when selection set does not include direct fields', async () => {
const result = await preset.buildGeneratesSection({
baseOutputDir: './src/',
Expand Down