-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
no-scalar-result-type-on-mutation.ts
74 lines (70 loc) · 2.08 KB
/
no-scalar-result-type-on-mutation.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { isScalarType, Kind, NameNode } from 'graphql';
import { GraphQLESTreeNode } from '../estree-converter/index.js';
import { GraphQLESLintRule } from '../types.js';
import { getNodeName, requireGraphQLSchemaFromContext } from '../utils.js';
const RULE_ID = 'no-scalar-result-type-on-mutation';
export const rule: GraphQLESLintRule = {
meta: {
type: 'suggestion',
hasSuggestions: true,
docs: {
category: 'Schema',
description:
'Avoid scalar result type on mutation type to make sure to return a valid state.',
url: `https://the-guild.dev/graphql/eslint/rules/${RULE_ID}`,
requiresSchema: true,
examples: [
{
title: 'Incorrect',
code: /* GraphQL */ `
type Mutation {
createUser: Boolean
}
`,
},
{
title: 'Correct',
code: /* GraphQL */ `
type Mutation {
createUser: User!
}
`,
},
],
},
schema: [],
},
create(context) {
const schema = requireGraphQLSchemaFromContext(RULE_ID, context);
const mutationType = schema.getMutationType();
if (!mutationType) {
return {};
}
const selector = [
`:matches(ObjectTypeDefinition, ObjectTypeExtension)[name.value=${mutationType.name}]`,
'> FieldDefinition > .gqlType Name',
].join(' ');
return {
[selector](node: GraphQLESTreeNode<NameNode>) {
const typeName = node.value;
const graphQLType = schema.getType(typeName);
if (isScalarType(graphQLType)) {
let fieldDef = node.parent as any;
while (fieldDef.kind !== Kind.FIELD_DEFINITION) {
fieldDef = fieldDef.parent;
}
context.report({
node,
message: `Unexpected scalar result type \`${typeName}\` for ${getNodeName(fieldDef)}`,
suggest: [
{
desc: `Remove \`${typeName}\``,
fix: fixer => fixer.remove(node as any),
},
],
});
}
},
};
},
};