UNPKG

@graphql-eslint/eslint-plugin

Version:
68 lines (67 loc) 2.62 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-anonymous-operations'; exports.rule = { meta: { type: 'suggestion', hasSuggestions: true, docs: { category: 'Operations', description: 'Require name for your GraphQL operations. This is useful since most GraphQL client libraries are using the operation name for caching purposes.', recommended: true, url: `https://github.com/B2o5T/graphql-eslint/blob/master/docs/rules/${RULE_ID}.md`, examples: [ { title: 'Incorrect', code: /* GraphQL */ ` query { # ... } `, }, { title: 'Correct', code: /* GraphQL */ ` query user { # ... } `, }, ], }, messages: { [RULE_ID]: 'Anonymous GraphQL operations are forbidden. Make sure to name your {{ operation }}!', }, schema: [], }, create(context) { return { 'OperationDefinition[name=undefined]'(node) { const [firstSelection] = node.selectionSet.selections; const suggestedName = firstSelection.kind === graphql_1.Kind.FIELD ? (firstSelection.alias || firstSelection.name).value : node.operation; context.report({ loc: (0, utils_js_1.getLocation)(node.loc.start, node.operation), messageId: RULE_ID, data: { operation: node.operation, }, suggest: [ { desc: `Rename to \`${suggestedName}\``, fix(fixer) { const sourceCode = context.getSourceCode(); const hasQueryKeyword = sourceCode.getText({ range: [node.range[0], node.range[0] + 1] }) !== '{'; return fixer.insertTextAfterRange([node.range[0], node.range[0] + (hasQueryKeyword ? node.operation.length : 0)], `${hasQueryKeyword ? '' : 'query'} ${suggestedName}${hasQueryKeyword ? '' : ' '}`); }, }, ], }); }, }; }, };