Skip to content

Commit

Permalink
fix defaultSerializeQueryArgs for nested objects (#1029)
Browse files Browse the repository at this point in the history
fix/default serialize query args
  • Loading branch information
phryneas authored Apr 30, 2021
2 parents 022988f + 1fa89a5 commit 6864454
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/query/defaultSerializeQueryArgs.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
import { QueryCacheKey } from './core/apiState'
import { EndpointDefinition } from './endpointDefinitions'
import { isPlainObject } from '@reduxjs/toolkit'

export const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({
endpointName,
queryArgs,
}) => {
// Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })
return `${endpointName}(${JSON.stringify(
queryArgs,
Object.keys(queryArgs || {}).sort()
return `${endpointName}(${JSON.stringify(queryArgs, (key, value) =>
isPlainObject(value)
? Object.keys(value)
.sort()
.reduce<any>((acc, key) => {
acc[key] = (value as any)[key]
return acc
}, {})
: value
)})`
}

Expand Down
46 changes: 46 additions & 0 deletions src/query/tests/defaultSerializeQueryArgs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { defaultSerializeQueryArgs } from '@internal/query/defaultSerializeQueryArgs'

const endpointDefinition: any = {}
const endpointName = 'test'

test('string arg', () => {
expect(
defaultSerializeQueryArgs({
endpointDefinition,
endpointName,
queryArgs: 'arg',
})
).toMatchInlineSnapshot(`"test(\\"arg\\")"`)
})

test('number arg', () => {
expect(
defaultSerializeQueryArgs({
endpointDefinition,
endpointName,
queryArgs: 5,
})
).toMatchInlineSnapshot(`"test(5)"`)
})

test('simple object arg is sorted', () => {
expect(
defaultSerializeQueryArgs({
endpointDefinition,
endpointName,
queryArgs: { name: 'arg', age: 5 },
})
).toMatchInlineSnapshot(`"test({\\"age\\":5,\\"name\\":\\"arg\\"})"`)
})

test('nested object arg is sorted recursively', () => {
expect(
defaultSerializeQueryArgs({
endpointDefinition,
endpointName,
queryArgs: { name: { last: 'Split', first: 'Banana' }, age: 5 },
})
).toMatchInlineSnapshot(
`"test({\\"age\\":5,\\"name\\":{\\"first\\":\\"Banana\\",\\"last\\":\\"Split\\"}})"`
)
})

0 comments on commit 6864454

Please sign in to comment.