feat(eslint-plugin-query): add prefer-query-options rule#10359
feat(eslint-plugin-query): add prefer-query-options rule#10359
Conversation
📝 WalkthroughWalkthroughAdds a new ESLint rule Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
View your CI Pipeline Execution ↗ for commit 26737a2
☁️ Nx Cloud last updated this comment at |
🚀 Changeset Version Preview1 package(s) bumped directly, 23 bumped as dependents. 🟨 Minor bumps
🟩 Patch bumps
|
size-limit report 📦
|
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@docs/eslint/prefer-query-options.md`:
- Around line 27-31: The examples (e.g., useFooQuery and the queryOptions(...)
snippets) reference id without any binding; change them into factory functions
that accept id (e.g., function useFooQuery(id) or export function
queryOptions(id)) and then pass that id into the useQuery call (or into
queryOptions(id)) so the id is in scope; update any example that builds
queryOptions(...) to be queryOptions(id) and update callers to pass the id into
useFooQuery or the options factory accordingly (references: useFooQuery,
queryOptions, options).
In
`@packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts`:
- Around line 23-30: The rule currently only flags inline options for methods in
queryClientOptionMethods but misses the newer APIs; add 'query' and
'infiniteQuery' to the queryClientOptionMethods array so inline options passed
to queryClient.query(...) and queryClient.infiniteQuery(...) are checked, and
update the test suite for this rule to include invalid cases covering query()
and infiniteQuery() (matching the existing invalid cases for
fetchQuery/fetchInfiniteQuery) so the select option behavior is asserted for
both legacy and new APIs; update any test matrix entries that reference method
names to include 'query' and 'infiniteQuery' as well.
- Around line 177-180: The rule currently checks options.type ===
AST_NODE_TYPES.ArrayExpression directly and misses TS assertion wrappers; update
the checks inside the prefer-query-options rule where queryClientQueryKeyMethods
is handled (and inside hasInlineFilterQueryKey) to first unwrap TypeScript
assertion nodes using the existing helper dereferenceVariablesAndTypeAssertions
(as used in exhaustive-deps.rule.ts) and then check the resulting node.type ===
AST_NODE_TYPES.ArrayExpression; add tests covering both "as const"
(TSAsExpression) and "satisfies" (TSSatisfiesExpression) forms to ensure these
assertion-wrapped array literals are recognized.
- Around line 75-76: The rule must stop relying on raw identifier text and
instead resolve symbols via import specifiers and scope bindings: update places
using isIdentifierWithOneOfNames, isIdentifierWithName, and the
queryClientVariables Set to resolve the node's binding (use
context.getScope()/sourceCode.getScope or eslint-utils findVariable) and then
verify the binding originates from a TanStack import via
helpers.isTanstackQueryImport by checking the ImportSpecifier/ImportDeclaration
and the imported.name (e.g., 'useQuery', 'useQueryClient', 'QueryClient'); when
tracking QueryClient results store the actual Variable/binding or the
ImportSpecifier reference instead of a string so membership checks are
scope-aware and won’t match shadowed parameters, and for aliased imports compare
the import specifier's imported.name to the canonical TanStack symbol names
rather than the local identifier text.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 3697aff5-b7ea-4d4f-a1de-925c4b9f3ac8
📒 Files selected for processing (8)
.changeset/prefer-query-options-rule.mddocs/config.jsondocs/eslint/eslint-plugin-query.mddocs/eslint/prefer-query-options.mdpackages/eslint-plugin-query/src/__tests__/prefer-query-options.test.tspackages/eslint-plugin-query/src/index.tspackages/eslint-plugin-query/src/rules.tspackages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts
packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts
Show resolved
Hide resolved
packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts
Outdated
Show resolved
Hide resolved
packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts
Show resolved
Hide resolved
…k/query into feat-eslint-prefer-query-options
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In
`@packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts`:
- Around line 78-94: The rule currently inspects nodes directly and misses
patterns wrapped in TypeScript assertions/satisfies; update
reportInlineQueryOptions and reportInlineFilterQueryKey to first call
unwrapTypeAssertions(node) and use the unwrapped node for
ASTUtils.isObjectExpression checks and subsequent
hasInlineQueryOptions/hasInlineFilterQueryKey evaluations, and likewise apply
unwrapTypeAssertions when traversing queries entries (the logic around the
queries array that checks each entry) so that asserted/satisfied
ObjectExpression/ArrayExpression forms are detected; keep existing messageIds
and only change the inspected node to the unwrapped result.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 3e887bb9-56cc-4d8e-be48-9e9b47c3ca38
📒 Files selected for processing (3)
docs/eslint/prefer-query-options.mdpackages/eslint-plugin-query/src/__tests__/prefer-query-options.test.tspackages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts
✅ Files skipped from review due to trivial changes (1)
- docs/eslint/prefer-query-options.md
| function reportInlineQueryOptions(node: TSESTree.Node): void { | ||
| if (ASTUtils.isObjectExpression(node) && hasInlineQueryOptions(node)) { | ||
| context.report({ | ||
| node, | ||
| messageId: 'preferQueryOptions', | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| function reportInlineFilterQueryKey(node: TSESTree.Node): void { | ||
| if (ASTUtils.isObjectExpression(node) && hasInlineFilterQueryKey(node)) { | ||
| context.report({ | ||
| node, | ||
| messageId: 'preferQueryOptionsQueryKey', | ||
| }) | ||
| } | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, locate and examine the target file
fd -t f "prefer-query-options.rule.ts" packages/eslint-plugin-queryRepository: TanStack/query
Length of output: 146
🏁 Script executed:
# Get the file size to determine how to read it
wc -l packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.tsRepository: TanStack/query
Length of output: 150
🏁 Script executed:
# Read the entire file to understand the implementation
cat -n packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.tsRepository: TanStack/query
Length of output: 12438
🏁 Script executed:
# Find test files for this rule
fd -t f "prefer-query-options" packages/eslint-plugin-query/src/rules --type fRepository: TanStack/query
Length of output: 146
🏁 Script executed:
# Look for test directory
fd -t d "__tests__" packages/eslint-plugin-query/src/rules/prefer-query-options/Repository: TanStack/query
Length of output: 40
🏁 Script executed:
# Find test files more broadly
fd "prefer-query-options" packages/eslint-plugin-query -type f | grep -i testRepository: TanStack/query
Length of output: 228
🏁 Script executed:
# Look for test files in the rules directory
find packages/eslint-plugin-query -name "*prefer-query-options*" -type fRepository: TanStack/query
Length of output: 218
🏁 Script executed:
# Read the test file
cat -n packages/eslint-plugin-query/src/__tests__/prefer-query-options.test.tsRepository: TanStack/query
Length of output: 39919
🏁 Script executed:
# Double-check the exact line ranges mentioned in the review comment
# Lines 124-127 (queriesHooks handling)
sed -n '124,127p' packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.tsRepository: TanStack/query
Length of output: 186
🏁 Script executed:
# Lines 210-288 (getReturnedObjectExpressions and getQueryObjects)
sed -n '210,288p' packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.tsRepository: TanStack/query
Length of output: 2039
🏁 Script executed:
# Verify unwrapTypeAssertions implementation
sed -n '379,389p' packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.tsRepository: TanStack/query
Length of output: 347
Unwrap asserted option objects before inspecting them.
unwrapTypeAssertions() only protects raw query-key arrays. Patterns like useQuery({ queryKey: ['todos'], queryFn: () => fetchTodos() } as const), queryClient.fetchQuery({ ... } satisfies SomeOptions), and useQueries({ queries: ([{ ... }] as const) }) bypass the rule because these paths still require a bare ObjectExpression/ArrayExpression. Add unwrapping before object checks and while traversing queries entries.
Suggested fix
function reportInlineQueryOptions(node: TSESTree.Node): void {
- if (ASTUtils.isObjectExpression(node) && hasInlineQueryOptions(node)) {
+ const expression = unwrapTypeAssertions(node)
+ if (
+ ASTUtils.isObjectExpression(expression) &&
+ hasInlineQueryOptions(expression)
+ ) {
context.report({
node,
messageId: 'preferQueryOptions',
})
}
}
function reportInlineFilterQueryKey(node: TSESTree.Node): void {
- if (ASTUtils.isObjectExpression(node) && hasInlineFilterQueryKey(node)) {
+ const expression = unwrapTypeAssertions(node)
+ if (
+ ASTUtils.isObjectExpression(expression) &&
+ hasInlineFilterQueryKey(expression)
+ ) {
context.report({
node,
messageId: 'preferQueryOptionsQueryKey',
})
}
}
@@
- if (
- queriesHooks.includes(importedName) &&
- ASTUtils.isObjectExpression(options)
- ) {
+ const expression = unwrapTypeAssertions(options)
+ if (
+ queriesHooks.includes(importedName) &&
+ ASTUtils.isObjectExpression(expression)
+ ) {
const queries = ASTUtils.findPropertyWithIdentifierKey(
- options.properties,
+ expression.properties,
'queries',
)?.value
@@
function getReturnedObjectExpressions(
node: TSESTree.Node,
): Array<TSESTree.ObjectExpression> {
+ node = unwrapTypeAssertions(node)
+
if (ASTUtils.isObjectExpression(node)) {
return [node]
}
@@
function getQueryObjects(
node: TSESTree.Node,
): Array<TSESTree.ObjectExpression> {
+ node = unwrapTypeAssertions(node)
+
if (node.type === AST_NODE_TYPES.ArrayExpression) {
- return node.elements.flatMap((element) => {
- if (element !== null && ASTUtils.isObjectExpression(element)) {
- return [element]
- }
-
- return []
- })
+ return node.elements.flatMap((element) =>
+ element === null ? [] : getReturnedObjectExpressions(element),
+ )
}Also applies to: 124-127, 210-288
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In
`@packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts`
around lines 78 - 94, The rule currently inspects nodes directly and misses
patterns wrapped in TypeScript assertions/satisfies; update
reportInlineQueryOptions and reportInlineFilterQueryKey to first call
unwrapTypeAssertions(node) and use the unwrapped node for
ASTUtils.isObjectExpression checks and subsequent
hasInlineQueryOptions/hasInlineFilterQueryKey evaluations, and likewise apply
unwrapTypeAssertions when traversing queries entries (the logic around the
queries array that checks each entry) so that asserted/satisfied
ObjectExpression/ArrayExpression forms are detected; keep existing messageIds
and only change the inspected node to the unwrapped result.
Prior discussion #8515
🎯 Changes
New ESLint rule
prefer-query-optionsthat enforces usingqueryOptions()/infiniteQueryOptions()to co-locate query keys and functions. A query key should be defined exactly once — the rule flags every place where a user types one manually.This is rule is stricter and more opinionated than the others, I also created
recommendedStrictconfig (flat/recommended-strict) which includes allrecommendedrules plus this rule.Examples:
✅ Checklist
pnpm run test:pr.🚀 Release Impact
Summary by CodeRabbit
New Features
Documentation
Tests
Chores