-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
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 a114b10
☁️ 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 46.38% 46.37% -0.01%
==========================================
Files 214 214
Lines 8488 8487 -1
Branches 1927 1919 -8
==========================================
- Hits 3937 3936 -1
Misses 4108 4108
Partials 443 443 🚀 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
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.
hello 🙃
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: serialize({ 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 Suggested reviewers
Assessment against linked issues
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing touches
🧪 Generate unit tests
Comment |
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.
|
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 (1)
packages/query-core/src/__tests__/hydration.test.tsx (1)
1385-1429
: Make the new key-serialization test less brittleThe toMatchObject assertion on Query instances can be fragile due to instance internals. You already assert queryKey and queryHash equality; that’s sufficient.
Apply:
expect(clientEntry.queryKey).toEqual(queryKey) expect(clientEntry.queryKey).toEqual(serverEntry.queryKey) expect(clientEntry.queryHash).toEqual(serverEntry.queryHash) - expect(clientEntry).toMatchObject(serverEntry)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
packages/query-core/package.json
(1 hunks)packages/query-core/src/__tests__/hydration.test.tsx
(10 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/query-core/package.json
🧰 Additional context used
🧬 Code graph analysis (1)
packages/query-core/src/__tests__/hydration.test.tsx (2)
packages/query-core/src/queryClient.ts (1)
QueryClient
(61-648)packages/query-core/src/hydration.ts (2)
dehydrate
(122-163)hydrate
(165-267)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Preview
- GitHub Check: Test
🔇 Additional comments (5)
packages/query-core/src/__tests__/hydration.test.tsx (5)
1-1
: Optional: Prefer Vitest’s assert over node:assert for consistencyImporting assert from vitest keeps all test utilities from the same source and avoids Node-specific ESM specifiers in tests.
Apply:
-import assert from 'node:assert' -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, test, vi, assert } from 'vitest'Also applies to: 4-4, 7-8
45-45
: No action needed (formatting-only change)Whitespace-only change.
972-996
: LGTM: superjson-based (de)serialization wired correctlyUsing serializeData/deserializeData with superjson ensures non-plain types (e.g., Date) round-trip for both data and queryKey.
Based on learnings
Also applies to: 1008-1032, 1044-1069
1208-1208
: LGTMThe client-side QueryClient instantiation here is fine and reads clearer.
1384-1384
: No action needed (formatting-only change)Whitespace-only change.
5d7869e
to
18a12ca
Compare
Serialize query keys the same way
.data
is serializedShould fix trpc/trpc#6802
Summary by CodeRabbit