UNPKG

@graphql-eslint/eslint-plugin

Version:
135 lines (130 loc) 3.65 kB
import "../chunk-BMTV3EA2.js"; import { TypeInfo, visit, visitWithTypeInfo } from "graphql"; import { requireGraphQLSchemaFromContext, requireSiblingsOperations } from "../utils.js"; const RULE_ID = "no-unused-fields"; let usedFieldsCache; function getUsedFields(schema, operations) { if (usedFieldsCache) { return usedFieldsCache; } const usedFields = /* @__PURE__ */ Object.create(null); const typeInfo = new TypeInfo(schema); const visitor = visitWithTypeInfo(typeInfo, { Field(node) { var _a; const fieldDef = typeInfo.getFieldDef(); if (!fieldDef) { return false; } const parentTypeName = typeInfo.getParentType().name; const fieldName = node.name.value; (_a = usedFields[parentTypeName]) != null ? _a : usedFields[parentTypeName] = /* @__PURE__ */ new Set(); usedFields[parentTypeName].add(fieldName); } }); const allDocuments = [...operations.getOperations(), ...operations.getFragments()]; for (const { document } of allDocuments) { visit(document, visitor); } usedFieldsCache = usedFields; return usedFieldsCache; } const rule = { meta: { messages: { [RULE_ID]: 'Field "{{fieldName}}" is unused' }, docs: { description: "Requires all fields to be used at some level by siblings operations.", category: "Schema", url: `https://the-guild.dev/graphql/eslint/rules/${RULE_ID}`, requiresSiblings: true, requiresSchema: true, isDisabledForAllConfig: true, examples: [ { title: "Incorrect", code: ( /* GraphQL */ ` type User { id: ID! name: String someUnusedField: String } type Query { me: User } query { me { id name } } ` ) }, { title: "Correct", code: ( /* GraphQL */ ` type User { id: ID! name: String } type Query { me: User } query { me { id name } } ` ) } ] }, type: "suggestion", schema: [], hasSuggestions: true }, create(context) { const schema = requireGraphQLSchemaFromContext(RULE_ID, context); const siblingsOperations = requireSiblingsOperations(RULE_ID, context); const usedFields = getUsedFields(schema, siblingsOperations); return { FieldDefinition(node) { var _a; const fieldName = node.name.value; const parentTypeName = node.parent.name.value; const isUsed = (_a = usedFields[parentTypeName]) == null ? void 0 : _a.has(fieldName); if (isUsed) { return; } context.report({ node: node.name, messageId: RULE_ID, data: { fieldName }, suggest: [ { desc: `Remove \`${fieldName}\` field`, fix(fixer) { const sourceCode = context.getSourceCode(); const tokenBefore = sourceCode.getTokenBefore(node); const tokenAfter = sourceCode.getTokenAfter(node); const isEmptyType = tokenBefore.type === "{" && tokenAfter.type === "}"; return fixer.remove(isEmptyType ? node.parent : node); } } ] }); } }; } }; export { rule };