| 1 | import type { QueryCacheKey } from './core/apiState'
|
|---|
| 2 | import type { EndpointDefinition } from './endpointDefinitions'
|
|---|
| 3 | import { isPlainObject } from './core/rtkImports'
|
|---|
| 4 |
|
|---|
| 5 | const cache: WeakMap<any, string> | undefined = WeakMap
|
|---|
| 6 | ? new WeakMap()
|
|---|
| 7 | : undefined
|
|---|
| 8 |
|
|---|
| 9 | export const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({
|
|---|
| 10 | endpointName,
|
|---|
| 11 | queryArgs,
|
|---|
| 12 | }) => {
|
|---|
| 13 | let serialized = ''
|
|---|
| 14 |
|
|---|
| 15 | const cached = cache?.get(queryArgs)
|
|---|
| 16 |
|
|---|
| 17 | if (typeof cached === 'string') {
|
|---|
| 18 | serialized = cached
|
|---|
| 19 | } else {
|
|---|
| 20 | const stringified = JSON.stringify(queryArgs, (key, value) => {
|
|---|
| 21 | // Handle bigints
|
|---|
| 22 | value = typeof value === 'bigint' ? { $bigint: value.toString() } : value
|
|---|
| 23 | // Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })
|
|---|
| 24 | value = isPlainObject(value)
|
|---|
| 25 | ? Object.keys(value)
|
|---|
| 26 | .sort()
|
|---|
| 27 | .reduce<any>((acc, key) => {
|
|---|
| 28 | acc[key] = (value as any)[key]
|
|---|
| 29 | return acc
|
|---|
| 30 | }, {})
|
|---|
| 31 | : value
|
|---|
| 32 | return value
|
|---|
| 33 | })
|
|---|
| 34 | if (isPlainObject(queryArgs)) {
|
|---|
| 35 | cache?.set(queryArgs, stringified)
|
|---|
| 36 | }
|
|---|
| 37 | serialized = stringified
|
|---|
| 38 | }
|
|---|
| 39 | return `${endpointName}(${serialized})`
|
|---|
| 40 | }
|
|---|
| 41 |
|
|---|
| 42 | export type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {
|
|---|
| 43 | queryArgs: QueryArgs
|
|---|
| 44 | endpointDefinition: EndpointDefinition<any, any, any, any>
|
|---|
| 45 | endpointName: string
|
|---|
| 46 | }) => ReturnType
|
|---|
| 47 |
|
|---|
| 48 | export type InternalSerializeQueryArgs = (_: {
|
|---|
| 49 | queryArgs: any
|
|---|
| 50 | endpointDefinition: EndpointDefinition<any, any, any, any>
|
|---|
| 51 | endpointName: string
|
|---|
| 52 | }) => QueryCacheKey
|
|---|