UNPKG

@graphql-eslint/eslint-plugin

Version:
131 lines (126 loc) 4.45 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.rule = void 0; const graphql_1 = require("graphql"); const utils_js_1 = require("../utils.js"); const RULE_ID = 'no-unused-fields'; let usedFieldsCache; function getUsedFields(schema, operations) { // We don't want cache usedFields on test environment // Otherwise usedFields will be same for all tests if (process.env.NODE_ENV !== 'test' && usedFieldsCache) { return usedFieldsCache; } const usedFields = Object.create(null); const typeInfo = new graphql_1.TypeInfo(schema); const visitor = (0, graphql_1.visitWithTypeInfo)(typeInfo, { Field(node) { var _a; const fieldDef = typeInfo.getFieldDef(); if (!fieldDef) { // skip visiting this node if field is not defined in schema return false; } const parentTypeName = typeInfo.getParentType().name; const fieldName = node.name.value; (_a = usedFields[parentTypeName]) !== null && _a !== void 0 ? _a : (usedFields[parentTypeName] = new Set()); usedFields[parentTypeName].add(fieldName); }, }); const allDocuments = [...operations.getOperations(), ...operations.getFragments()]; for (const { document } of allDocuments) { (0, graphql_1.visit)(document, visitor); } usedFieldsCache = usedFields; return usedFieldsCache; } exports.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://github.com/B2o5T/graphql-eslint/blob/master/docs/rules/${RULE_ID}.md`, 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 = (0, utils_js_1.requireGraphQLSchemaFromContext)(RULE_ID, context); const siblingsOperations = (0, utils_js_1.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 || _a === void 0 ? 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)); }, }, ], }); }, }; }, };