|
| 1 | +import { Kind, ObjectTypeDefinitionNode } from 'graphql'; |
| 2 | +import { GraphQLESLintRule } from '../types.js'; |
| 3 | +import { getNodeName, requireGraphQLSchemaFromContext, truthy } from '../utils.js'; |
| 4 | +import { GraphQLESTreeNode } from '../estree-converter/index.js'; |
| 5 | + |
| 6 | +const RULE_ID = 'require-nullable-result-in-root'; |
| 7 | + |
| 8 | +export const rule: GraphQLESLintRule = { |
| 9 | + meta: { |
| 10 | + type: 'suggestion', |
| 11 | + hasSuggestions: true, |
| 12 | + docs: { |
| 13 | + category: 'Schema', |
| 14 | + description: 'Require nullable fields in root types.', |
| 15 | + url: `https://github.com/B2o5T/graphql-eslint/blob/master/docs/rules/${RULE_ID}.md`, |
| 16 | + requiresSchema: true, |
| 17 | + examples: [ |
| 18 | + { |
| 19 | + title: 'Incorrect', |
| 20 | + code: /* GraphQL */ ` |
| 21 | + type Query { |
| 22 | + user: User! |
| 23 | + } |
| 24 | + `, |
| 25 | + }, |
| 26 | + { |
| 27 | + title: 'Correct', |
| 28 | + code: /* GraphQL */ ` |
| 29 | + type Query { |
| 30 | + foo: User |
| 31 | + baz: [User]! |
| 32 | + bar: [User!]! |
| 33 | + } |
| 34 | + `, |
| 35 | + }, |
| 36 | + ], |
| 37 | + }, |
| 38 | + messages: { |
| 39 | + [RULE_ID]: 'Unexpected non-null result {{ resultType }} in {{ rootType }}', |
| 40 | + }, |
| 41 | + schema: [], |
| 42 | + }, |
| 43 | + create(context) { |
| 44 | + const schema = requireGraphQLSchemaFromContext(RULE_ID, context); |
| 45 | + const rootTypeNames = new Set( |
| 46 | + [schema.getQueryType(), schema.getMutationType(), schema.getSubscriptionType()] |
| 47 | + .filter(truthy) |
| 48 | + .map(type => type.name), |
| 49 | + ); |
| 50 | + const sourceCode = context.getSourceCode(); |
| 51 | + |
| 52 | + return { |
| 53 | + 'ObjectTypeDefinition,ObjectTypeExtension'( |
| 54 | + node: GraphQLESTreeNode<ObjectTypeDefinitionNode>, |
| 55 | + ) { |
| 56 | + if (!rootTypeNames.has(node.name.value)) return; |
| 57 | + |
| 58 | + for (const field of node.fields || []) { |
| 59 | + if ( |
| 60 | + field.gqlType.type !== Kind.NON_NULL_TYPE || |
| 61 | + field.gqlType.gqlType.type !== Kind.NAMED_TYPE |
| 62 | + ) |
| 63 | + continue; |
| 64 | + const name = field.gqlType.gqlType.name.value; |
| 65 | + const type = schema.getType(name); |
| 66 | + const resultType = type ? getNodeName(type.astNode as any) : ''; |
| 67 | + |
| 68 | + context.report({ |
| 69 | + node: field.gqlType, |
| 70 | + messageId: RULE_ID, |
| 71 | + data: { |
| 72 | + resultType, |
| 73 | + rootType: getNodeName(node), |
| 74 | + }, |
| 75 | + suggest: [ |
| 76 | + { |
| 77 | + desc: `Make ${resultType} nullable`, |
| 78 | + fix(fixer) { |
| 79 | + const text = sourceCode.getText(field.gqlType as any); |
| 80 | + |
| 81 | + return fixer.replaceText(field.gqlType as any, text.replace('!', '')); |
| 82 | + }, |
| 83 | + }, |
| 84 | + ], |
| 85 | + }); |
| 86 | + } |
| 87 | + }, |
| 88 | + }; |
| 89 | + }, |
| 90 | +}; |
0 commit comments