UNPKG

@graphql-eslint/eslint-plugin

Version:
99 lines (98 loc) 3.27 kB
"use strict"; 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 no_anonymous_operations_exports = {}; __export(no_anonymous_operations_exports, { rule: () => rule }); module.exports = __toCommonJS(no_anonymous_operations_exports); var import_graphql = require("graphql"); var import_utils = require("../utils.js"); const RULE_ID = "no-anonymous-operations"; const 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://the-guild.dev/graphql/eslint/rules/${RULE_ID}`, 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 === import_graphql.Kind.FIELD ? (firstSelection.alias || firstSelection.name).value : node.operation; context.report({ loc: (0, import_utils.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 ? "" : " "}` ); } } ] }); } }; } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { rule });