|
| 1 | +import { GraphQLESLintRule } from '../types'; |
| 2 | +import { requireSiblingsOperations } from '@graphql-eslint/eslint-plugin'; |
| 3 | +import { CWD } from '../utils'; |
| 4 | +import { relative } from 'path'; |
| 5 | +import { GraphQLESTreeNode } from '../estree-converter'; |
| 6 | +import { NameNode, visit } from 'graphql'; |
| 7 | + |
| 8 | +const RULE_ID = 'no-one-place-fragments'; |
| 9 | + |
| 10 | +export const rule: GraphQLESLintRule = { |
| 11 | + meta: { |
| 12 | + type: 'suggestion', |
| 13 | + docs: { |
| 14 | + category: 'Operations', |
| 15 | + description: 'Disallow fragments that are used only in one place.', |
| 16 | + url: `https://github.com/B2o5T/graphql-eslint/blob/master/docs/rules/${RULE_ID}.md`, |
| 17 | + examples: [ |
| 18 | + { |
| 19 | + title: 'Incorrect', |
| 20 | + code: /* GraphQL */ ` |
| 21 | + fragment UserFields on User { |
| 22 | + id |
| 23 | + } |
| 24 | +
|
| 25 | + { |
| 26 | + user { |
| 27 | + ...UserFields |
| 28 | + friends { |
| 29 | + ...UserFields |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + `, |
| 34 | + }, |
| 35 | + { |
| 36 | + title: 'Correct', |
| 37 | + code: /* GraphQL */ ` |
| 38 | + fragment UserFields on User { |
| 39 | + id |
| 40 | + } |
| 41 | +
|
| 42 | + { |
| 43 | + user { |
| 44 | + ...UserFields |
| 45 | + } |
| 46 | + } |
| 47 | + `, |
| 48 | + }, |
| 49 | + ], |
| 50 | + requiresSiblings: true, |
| 51 | + }, |
| 52 | + messages: { |
| 53 | + [RULE_ID]: 'Fragment `{{fragmentName}}` used only once. Inline him in "{{filePath}}".', |
| 54 | + }, |
| 55 | + schema: [], |
| 56 | + }, |
| 57 | + create(context) { |
| 58 | + const operations = requireSiblingsOperations(RULE_ID, context); |
| 59 | + const allDocuments = [...operations.getOperations(), ...operations.getFragments()]; |
| 60 | + |
| 61 | + const usedFragmentsMap: Record<string, string[]> = Object.create(null); |
| 62 | + |
| 63 | + for (const { document, filePath } of allDocuments) { |
| 64 | + const relativeFilePath = relative(CWD, filePath); |
| 65 | + visit(document, { |
| 66 | + FragmentSpread({ name }) { |
| 67 | + const spreadName = name.value; |
| 68 | + usedFragmentsMap[spreadName] ||= []; |
| 69 | + usedFragmentsMap[spreadName].push(relativeFilePath); |
| 70 | + }, |
| 71 | + }); |
| 72 | + } |
| 73 | + |
| 74 | + return { |
| 75 | + 'FragmentDefinition > Name'(node: GraphQLESTreeNode<NameNode>) { |
| 76 | + const fragmentName = node.value; |
| 77 | + const fragmentUsage = usedFragmentsMap[fragmentName]; |
| 78 | + |
| 79 | + if (fragmentUsage.length === 1) { |
| 80 | + context.report({ |
| 81 | + node, |
| 82 | + messageId: RULE_ID, |
| 83 | + data: { fragmentName, filePath: fragmentUsage[0] }, |
| 84 | + }); |
| 85 | + } |
| 86 | + }, |
| 87 | + }; |
| 88 | + }, |
| 89 | +}; |
0 commit comments