Skip to content

Commit

Permalink
Guard against duplicate fragment names in near-operations-file (#2139)
Browse files Browse the repository at this point in the history
  • Loading branch information
mvestergaard authored and dotansimha committed Jul 11, 2019
1 parent 5030593 commit bcdd04f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
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

0 comments on commit bcdd04f

Please sign in to comment.