@graphql-eslint/eslint-plugin
Version:
GraphQL plugin for ESLint
110 lines (109 loc) • 3.63 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var require_nullable_result_in_root_exports = {};
__export(require_nullable_result_in_root_exports, {
rule: () => rule
});
module.exports = __toCommonJS(require_nullable_result_in_root_exports);
var import_graphql = require("graphql");
var import_utils = require("../utils.js");
const RULE_ID = "require-nullable-result-in-root";
const rule = {
meta: {
type: "suggestion",
hasSuggestions: true,
docs: {
category: "Schema",
description: "Require nullable fields in root types.",
url: `https://the-guild.dev/graphql/eslint/rules/${RULE_ID}`,
requiresSchema: true,
examples: [
{
title: "Incorrect",
code: (
/* GraphQL */
`
type Query {
user: User!
}
`
)
},
{
title: "Correct",
code: (
/* GraphQL */
`
type Query {
foo: User
baz: [User]!
bar: [User!]!
}
`
)
}
]
},
messages: {
[RULE_ID]: "Unexpected non-null result {{ resultType }} in {{ rootType }}"
},
schema: []
},
create(context) {
const schema = (0, import_utils.requireGraphQLSchemaFromContext)(RULE_ID, context);
const rootTypeNames = new Set(
[schema.getQueryType(), schema.getMutationType(), schema.getSubscriptionType()].filter(import_utils.truthy).map((type) => type.name)
);
const sourceCode = context.getSourceCode();
return {
"ObjectTypeDefinition,ObjectTypeExtension"(node) {
if (!rootTypeNames.has(node.name.value))
return;
for (const field of node.fields || []) {
if (field.gqlType.type !== import_graphql.Kind.NON_NULL_TYPE || field.gqlType.gqlType.type !== import_graphql.Kind.NAMED_TYPE)
continue;
const name = field.gqlType.gqlType.name.value;
const type = schema.getType(name);
const resultType = (type == null ? void 0 : type.astNode) ? (0, import_utils.getNodeName)(type.astNode) : type == null ? void 0 : type.name;
context.report({
node: field.gqlType,
messageId: RULE_ID,
data: {
resultType: resultType || "",
rootType: (0, import_utils.getNodeName)(node)
},
suggest: [
{
desc: `Make ${resultType} nullable`,
fix(fixer) {
const text = sourceCode.getText(field.gqlType);
return fixer.replaceText(field.gqlType, text.replace("!", ""));
}
}
]
});
}
}
};
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
rule
});