@graphql-eslint/eslint-plugin
Version:
GraphQL plugin for ESLint
102 lines (99 loc) • 3.28 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: !0 });
}, __copyProps = (to, from, except, desc) => {
if (from && typeof from == "object" || typeof from == "function")
for (let key of __getOwnPropNames(from))
!__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: !0 }), mod);
var no_one_place_fragments_exports = {};
__export(no_one_place_fragments_exports, {
rule: () => rule
});
module.exports = __toCommonJS(no_one_place_fragments_exports);
var import_node_path = require("node:path"), import_graphql = require("graphql"), import_utils = require("../utils.js");
const RULE_ID = "no-one-place-fragments", rule = {
meta: {
type: "suggestion",
docs: {
category: "Operations",
description: "Disallow fragments that are used only in one place.",
url: `https://the-guild.dev/graphql/eslint/rules/${RULE_ID}`,
examples: [
{
title: "Incorrect",
code: (
/* GraphQL */
`
fragment UserFields on User {
id
}
{
user {
...UserFields
}
}
`
)
},
{
title: "Correct",
code: (
/* GraphQL */
`
fragment UserFields on User {
id
}
{
user {
...UserFields
friends {
...UserFields
}
}
}
`
)
}
],
requiresSiblings: !0
},
messages: {
[RULE_ID]: 'Fragment `{{fragmentName}}` used only once. Inline him in "{{filePath}}".'
},
schema: []
},
create(context) {
const operations = (0, import_utils.requireSiblingsOperations)(RULE_ID, context), allDocuments = [...operations.getOperations(), ...operations.getFragments()], usedFragmentsMap = /* @__PURE__ */ Object.create(null);
for (const { document, filePath } of allDocuments) {
const relativeFilePath = (0, import_node_path.relative)(import_utils.CWD, filePath);
(0, import_graphql.visit)(document, {
FragmentSpread({ name }) {
const spreadName = name.value;
usedFragmentsMap[spreadName] ||= [], usedFragmentsMap[spreadName].push(relativeFilePath);
}
});
}
return {
"FragmentDefinition > Name"(node) {
const fragmentName = node.value, fragmentUsage = usedFragmentsMap[fragmentName];
fragmentUsage.length === 1 && context.report({
node,
messageId: RULE_ID,
data: { fragmentName, filePath: fragmentUsage[0] }
});
}
};
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
rule
});