Skip to content

Commit e365ea5

Browse files
committed
fix(graphql): generate fields as optional when they contain arguments
Fields with arguments are usually resolved using a separate method with the @ResolveField() annotation. Having such field generated as a required property thus proves quite cumbersome as it forces assigning a value in the result of parent @query() method. This makes fields with arguments always optional.
1 parent 4e7568d commit e365ea5

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

packages/graphql/lib/graphql-ast.explorer.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,8 @@ export class GraphQLAstExplorer {
314314
return {
315315
name: propertyName,
316316
type: this.addSymbolIfRoot(type),
317-
hasQuestionToken: !required,
317+
hasQuestionToken:
318+
!required || (item as FieldDefinitionNode).arguments?.length > 0,
318319
};
319320
}
320321

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { GraphQLAstExplorer } from '../lib';
2+
import { gql } from 'graphql-tag';
3+
4+
describe('GraphQLAstExplorer', () => {
5+
describe('explore', () => {
6+
it('should generate fields as optional when they contain arguments', () => {
7+
const astExplorer = new GraphQLAstExplorer();
8+
9+
const document = gql`
10+
type Cat {
11+
id: Int!
12+
name: String!
13+
weight(unit: String!): Int!
14+
}
15+
16+
type Query {
17+
cat(id: ID!): Cat
18+
}
19+
`;
20+
21+
astExplorer
22+
.explore(document, '/dev/null', 'interface', {})
23+
.then((sourceFile) => {
24+
expect(
25+
sourceFile
26+
.getStructure()
27+
.statements[0].properties.find((prop) => prop.name === 'weight')!
28+
.hasQuestionToken,
29+
).toBe(true);
30+
});
31+
});
32+
});
33+
});

0 commit comments

Comments
 (0)