@graphql-eslint/eslint-plugin
Version:
GraphQL plugin for ESLint
122 lines (121 loc) • 3.54 kB
JavaScript
import path from "node:path";
import { requireGraphQLOperations, slash } from "../../utils.js";
const RULE_ID = "require-import-fragment", SUGGESTION_ID = "add-import-expression", rule = {
meta: {
type: "suggestion",
docs: {
category: "Operations",
description: "Require fragments to be imported via an import expression.",
url: `https://the-guild.dev/graphql/eslint/rules/${RULE_ID}`,
examples: [
{
title: "Incorrect",
code: (
/* GraphQL */
`
query {
user {
...UserFields
}
}
`
)
},
{
title: "Incorrect",
code: (
/* GraphQL */
`
# import 'post-fields.fragment.graphql'
query {
user {
...UserFields
}
}
`
)
},
{
title: "Incorrect",
code: (
/* GraphQL */
`
# import UserFields from 'post-fields.fragment.graphql'
query {
user {
...UserFields
}
}
`
)
},
{
title: "Correct",
code: (
/* GraphQL */
`
# import UserFields from 'user-fields.fragment.graphql'
query {
user {
...UserFields
}
}
`
)
}
],
requiresSiblings: !0
},
hasSuggestions: !0,
messages: {
[RULE_ID]: 'Expected "{{fragmentName}}" fragment to be imported.',
[SUGGESTION_ID]: 'Add import expression for "{{fragmentName}}".'
},
schema: []
},
create(context) {
const comments = context.getSourceCode().getAllComments(), siblings = requireGraphQLOperations(RULE_ID, context), filePath = context.filename;
return {
"FragmentSpread > .name"(node) {
const fragmentName = node.value, fragmentsFromSiblings = siblings.getFragment(fragmentName);
for (const comment of comments) {
if (comment.type !== "Line" || !new RegExp(
`^\\s*import\\s+(${fragmentName}\\s+from\\s+)?['"]`
).test(comment.value)) continue;
const extractedImportPath = comment.value.match(/(["'])((?:\1|.)*?)\1/)?.[2];
if (!extractedImportPath) continue;
const importPath = path.join(filePath, "..", extractedImportPath);
if (fragmentsFromSiblings.some(
(source) => source.filePath === importPath
)) return;
}
if (fragmentsFromSiblings.some(
(source) => source.filePath === filePath
)) return;
const suggestedFilePaths = fragmentsFromSiblings.length ? fragmentsFromSiblings.map(
(o) => (
// Use always forward slash for suggested import path
slash(path.relative(path.dirname(filePath), o.filePath))
)
) : ["CHANGE_ME.graphql"];
context.report({
node,
messageId: RULE_ID,
data: { fragmentName },
suggest: suggestedFilePaths.map((suggestedPath) => ({
messageId: SUGGESTION_ID,
data: { fragmentName },
fix: (fixer) => fixer.insertTextBeforeRange(
[0, 0],
`# import ${fragmentName} from '${suggestedPath}'
`
)
}))
});
}
};
}
};
export {
rule
};