-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsingular.mutations.js
More file actions
89 lines (77 loc) · 2 KB
/
singular.mutations.js
File metadata and controls
89 lines (77 loc) · 2 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const { visit, getLocation } = require('graphql/language');
const pluralize = require('pluralize');
const isPluralized = name => {
const pluralized = pluralize(name);
return name === pluralized;
};
const getMessage = (text, name, start) => {
const message = `Mutation '${name}' is plural. It's better to use singular mutations.`;
const location = getLocation({ body: text }, start);
return {
message,
line: location.line,
column: location.column,
ruleId: 'singular.mutations',
severity: 1
};
};
function getMutationNames(ast) {
const mutationNames = [];
visit(ast, {
ObjectTypeExtension(node) {
if (
node.name.value !== 'Mutation' ||
node.name.value === 'GraphQLMutation'
) {
return;
}
visit(node, {
FieldDefinition(node) {
mutationNames.push(node.type.name.value);
}
});
},
ObjectTypeDefinition(node) {
if (
node.name.value === 'Mutation' ||
node.name.value === 'GraphQLMutation'
) {
mutationNames.push(node.name.value);
}
}
});
return mutationNames;
}
module.exports = function(ast, text) {
const messages = [];
const mutationNames = getMutationNames(ast);
visit(ast, {
ObjectTypeDefinition(node) {
if (mutationNames.indexOf(node.name.value) < 0) {
return;
}
visit(node, {
FieldDefinition(node) {
const name = node.name.value;
if (isPluralized(name)) {
messages.push(getMessage(text, name, node.name.loc.start));
}
}
});
},
OperationDefinition(node) {
if (node.operation !== 'mutation') {
return;
}
node.selectionSet.selections.forEach(selection => {
if (selection.kind === 'Field') {
const name = selection.name.value;
if (isPluralized(name)) {
messages.push(getMessage(text, name, selection.name.loc.start));
}
}
});
}
});
return messages;
};