UNPKG

@graphql-eslint/eslint-plugin

Version:
87 lines (84 loc) 2.42 kB
import { relative } from "node:path"; import { Kind } from "graphql"; import { CWD, requireGraphQLOperations, slash, VIRTUAL_DOCUMENT_REGEX } from "../../utils.js"; const RULE_ID = "unique-fragment-name", checkNode = (context, node, ruleId) => { const documentName = node.name.value, siblings = requireGraphQLOperations(ruleId, context), siblingDocuments = node.kind === Kind.FRAGMENT_DEFINITION ? siblings.getFragment(documentName) : siblings.getOperation(documentName), filepath = context.filename, conflictingDocuments = siblingDocuments.filter((f) => { const isSameName = f.document.name?.value === documentName, isSamePath = slash(f.filePath) === slash(filepath); return isSameName && !isSamePath; }); conflictingDocuments.length > 0 && context.report({ messageId: ruleId, data: { documentName, summary: conflictingDocuments.map((f) => ` ${relative(CWD, f.filePath.replace(VIRTUAL_DOCUMENT_REGEX, ""))}`).join(` `) }, // @ts-expect-error name will exist node: node.name }); }, rule = { meta: { type: "suggestion", docs: { category: "Operations", description: "Enforce unique fragment names across your project.", url: `https://the-guild.dev/graphql/eslint/rules/${RULE_ID}`, requiresSiblings: !0, recommended: !0, examples: [ { title: "Incorrect", code: ( /* GraphQL */ ` # user.fragment.graphql fragment UserFields on User { id name fullName } # user-fields.graphql fragment UserFields on User { id } ` ) }, { title: "Correct", code: ( /* GraphQL */ ` # user.fragment.graphql fragment AllUserFields on User { id name fullName } # user-fields.graphql fragment UserFields on User { id } ` ) } ] }, messages: { [RULE_ID]: `Fragment named "{{ documentName }}" already defined in: {{ summary }}` }, schema: [] }, create(context) { return { FragmentDefinition(node) { checkNode(context, node, RULE_ID); } }; } }; export { checkNode, rule };