-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
fix: serialize queryKey
#9308
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
fix: serialize queryKey
#9308
Conversation
View your CI Pipeline Execution ↗ for commit 33df077
☁️ Nx Cloud last updated this comment at |
expect(serializeDataMock).toHaveBeenCalledTimes(1) | ||
expect(serializeDataMock).toHaveBeenCalledWith(0) | ||
|
||
expect(deserializeDataMock).toHaveBeenCalledTimes(1) | ||
expect(deserializeDataMock).toHaveBeenCalledWith(0) | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Removed these as the test isn't about whether if serialization is about and the amount of times the mock gets called doubled so it gets a bit weird and unintuitive anyway
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #9308 +/- ##
==========================================
- Coverage 45.15% 45.14% -0.01%
==========================================
Files 208 208
Lines 8323 8322 -1
Branches 1886 1876 -10
==========================================
- Hits 3758 3757 -1
Misses 4118 4118
Partials 447 447 🚀 New features to boost your workflow:
|
@@ -1,9 +1,11 @@ | |||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' | |||
import assert from 'node:assert' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should this come from vitest
?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's please hold off merging this until I'm back from vacation. Not sure if this is the right fix
WalkthroughDehydrate now serializes queryKey and data; hydrate deserializes queryKey/data, updates or rebuilds queries, and may re-use an initial promise to retry fetches. Tests switch to superjson for round-tripping non-primitive keys and add a test for Date-containing query keys. package.json adds superjson devDependency. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Server
participant Serializer as serializeData (superjson)
participant Transport
participant Client
participant Hydrator as hydrate()
participant Cache as QueryCache
Server->>Serializer: dehydrate({ queryKey, data, ... })
Serializer-->>Server: { serializedKey, serializedData, ... }
Server->>Transport: send dehydrated payload
Transport-->>Client: dehydrated payload
Client->>Hydrator: hydrate(payload, { deserializeData })
note right of Hydrator #DDEBF7: deserialize queryKey & data
Hydrator->>Hydrator: deserializeQueryKey(), deserializeData()
alt query exists in Cache
Hydrator->>Cache: update state if dehydrated/newer (preserve fetchStatus)
else
Hydrator->>Cache: create query with deserialized key/meta and set state
end
opt initial promise present & eligible
Hydrator->>Cache: attach initialPromise.then(deserializeData) -> retry fetch
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Assessment against linked issues
Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. 📜 Recent review detailsConfiguration used: CodeRabbit UI 💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration. ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
✨ Finishing Touches🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (3)
packages/query-core/src/hydration.ts (2)
89-91
: Serializing queryKey changes the dehydrated payload shape — document and/or adjust typingBy setting
queryKey: serializeData(query.queryKey)
, the dehydrated payload can now contain a non-QueryKey shape (e.g., superjson’s{ json, meta }
). However,DehydratedQuery.queryKey
is typed asQueryKey
(an array), which can mislead consumers who inspectdehydrated.queries
on the server. At minimum, document thatqueryKey
is serialized; optionally, widen the type to reflect reality.Proposed doc update (outside the changed hunk):
// In interface DehydratedQuery /** * Note: `queryKey` is serialized using the same transformer as `.state.data` * during dehydration and must be deserialized on hydration. Its runtime shape * may not be `QueryKey` until deserialized. */ interface DehydratedQuery { queryHash: string // consider: queryKey: unknown queryKey: QueryKey ... }If you want stricter correctness, consider changing the type to
unknown
and adapting internal usages. This would be a minor typing break for anyone accessingdehydrated.queries[i].queryKey
directly, so weigh it against compatibility.
201-205
: Defensive deserialization of queryKey to avoid hydration crashesIf a consumer mismatches serializers between dehydrate and hydrate,
deserializeData(nextQuery.queryKey)
can throw. A small guard prevents hard failures during hydration and falls back to the raw value.Apply this diff:
- const data = rawData === undefined ? rawData : deserializeData(rawData) - const queryKey = deserializeData(nextQuery.queryKey) + const data = rawData === undefined ? rawData : deserializeData(rawData) + let queryKey: QueryKey + try { + queryKey = deserializeData(nextQuery.queryKey) as QueryKey + } catch { + // Fallback for older payloads or mismatched serializers + queryKey = nextQuery.queryKey as unknown as QueryKey + }packages/query-core/src/__tests__/hydration.test.tsx (1)
1-4
: Minor: prefer using vitest’s expect over node:assert for consistencyThe helper using Node’s assert is fine, but the suite predominantly uses
expect
. Consider inlining it withexpect(entry).toBeTruthy()
to keep a single assertion style.-import assert from 'node:assert' ... - const getFirstEntry = (client: QueryClient) => { - const [entry] = client.getQueryCache().getAll() - assert(entry, 'cache should not be empty') - return entry - } + const getFirstEntry = (client: QueryClient) => { + const [entry] = client.getQueryCache().getAll() + expect(entry).toBeTruthy() + return entry! + }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
⛔ Files ignored due to path filters (1)
pnpm-lock.yaml
is excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (3)
packages/query-core/package.json
(1 hunks)packages/query-core/src/__tests__/hydration.test.tsx
(10 hunks)packages/query-core/src/hydration.ts
(2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/query-core/src/__tests__/hydration.test.tsx (1)
packages/query-core/src/hydration.ts (2)
dehydrate
(122-163)hydrate
(165-267)
packages/query-core/src/hydration.ts (2)
packages/query-core/src/query.ts (1)
promise
(198-200)packages/query-core/src/thenable.ts (1)
tryResolveSync
(94-111)
🔇 Additional comments (4)
packages/query-core/package.json (1)
63-65
: Add devDependency for superjson — looks goodAdding superjson under devDependencies is appropriate since it's only used in tests. No runtime impact.
packages/query-core/src/hydration.ts (1)
249-265
: Initial promise reuse is sound; confirm serializer symmetry for promise payloadsReusing the server-side
promise
withinitialPromise: Promise.resolve(promise).then(deserializeData)
is aligned with the earlier serialization viaquery.promise?.then(serializeData)
. Please ensure docs/examples emphasize that consumers must pass symmetricalserializeData
/deserializeData
functions for both data and keys to avoid mismatch in restored data and query hash.Would you like me to add a short docs snippet to the README explaining that both
data
andqueryKey
now use the same serializers and must be configured together?packages/query-core/src/__tests__/hydration.test.tsx (2)
971-979
: Consistent use of superjson in tests — good coverageSwitching to superjson for serialize/deserialize in tests accurately validates round-tripping of non-primitive data and keys. This meaningfully exercises the new behavior.
Also applies to: 988-994, 1007-1015, 1024-1030, 1043-1050, 1063-1067
1384-1429
: Great end-to-end test for non-plain query keysThe test asserting key equality and hash parity across dehydrate/hydrate with a Date in the key is exactly what we needed. This should prevent regressions for the linked issue.
Serialize query keys the same way
.data
is serializedShould fix trpc/trpc#6802
Summary by CodeRabbit