@graphql-eslint/eslint-plugin
Version:
GraphQL plugin for ESLint
85 lines (82 loc) • 3.12 kB
JavaScript
Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _graphql = require('graphql');
var _utilsjs = 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 = _utilsjs.requireGraphQLSchema.call(void 0, RULE_ID, context);
const rootTypeNames = new Set(
[schema.getQueryType(), schema.getMutationType()].filter((v) => !!v).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 !== _graphql.Kind.NON_NULL_TYPE || field.gqlType.gqlType.type !== _graphql.Kind.NAMED_TYPE)
continue;
const name = field.gqlType.gqlType.name.value;
const type = schema.getType(name);
const resultType = _optionalChain([type, 'optionalAccess', _ => _.astNode]) ? _utilsjs.getNodeName.call(void 0, type.astNode) : _optionalChain([type, 'optionalAccess', _2 => _2.name]);
context.report({
node: field.gqlType,
messageId: RULE_ID,
data: {
resultType: resultType || "",
rootType: _utilsjs.getNodeName.call(void 0, node)
},
suggest: [
{
desc: `Make ${resultType} nullable`,
fix(fixer) {
const text = sourceCode.getText(field.gqlType);
return fixer.replaceText(field.gqlType, text.replace("!", ""));
}
}
]
});
}
}
};
}
};
exports.rule = rule;
;