@graphql-eslint/eslint-plugin
Version:
GraphQL plugin for ESLint
114 lines (109 loc) • 3.3 kB
JavaScript
import "../chunk-U3TKCM4X.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), typeInfo = new TypeInfo(schema), visitor = visitWithTypeInfo(typeInfo, {
Field(node) {
if (!typeInfo.getFieldDef())
return !1;
const parentTypeName = typeInfo.getParentType().name, fieldName = node.name.value;
usedFields[parentTypeName] ??= /* @__PURE__ */ new Set(), usedFields[parentTypeName].add(fieldName);
}
}), allDocuments = [...operations.getOperations(), ...operations.getFragments()];
for (const { document } of allDocuments)
visit(document, visitor);
return usedFieldsCache = usedFields, 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: !0,
requiresSchema: !0,
// Requires documents to be set
isDisabledForAllConfig: !0,
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: !0
},
create(context) {
const schema = requireGraphQLSchemaFromContext(RULE_ID, context), siblingsOperations = requireSiblingsOperations(RULE_ID, context), usedFields = getUsedFields(schema, siblingsOperations);
return {
FieldDefinition(node) {
const fieldName = node.name.value, parentTypeName = node.parent.name.value;
usedFields[parentTypeName]?.has(fieldName) || context.report({
node: node.name,
messageId: RULE_ID,
data: { fieldName },
suggest: [
{
desc: `Remove \`${fieldName}\` field`,
fix(fixer) {
const sourceCode = context.getSourceCode(), tokenBefore = sourceCode.getTokenBefore(node), tokenAfter = sourceCode.getTokenAfter(node), isEmptyType = tokenBefore.type === "{" && tokenAfter.type === "}";
return fixer.remove(isEmptyType ? node.parent : node);
}
}
]
});
}
};
}
};
export {
rule
};