Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions packages/toolkit/.size-limit.cjs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
const webpack = require('webpack')
let { join } = require('path')

const esmSuffixes = ['modern.mjs' /*, 'browser.mjs', 'legacy-esm.js'*/]
const cjsSuffixes = [/*'development.cjs',*/ 'production.min.cjs']
const esmSuffixes = ['modern.mjs', 'browser.mjs' /*, 'legacy-esm.js'*/]
const cjsSuffixes = [
/*'development.cjs',*/
/*'production.min.cjs'*/
]

function withRtkPath(suffix, cjs = false) {
/**
Expand Down
10 changes: 9 additions & 1 deletion packages/toolkit/src/query/apiTypes.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { UnknownAction } from '@reduxjs/toolkit'
import type { BaseQueryFn } from './baseQueryTypes'
import type { CombinedState, CoreModule } from './core'
import type { CombinedState, CoreModule, QueryKeys } from './core'
import type { ApiModules } from './core/module'
import type { CreateApiOptions } from './createApi'
import type {
Expand Down Expand Up @@ -56,6 +56,14 @@ export interface ApiContext<Definitions extends EndpointDefinitions> {
hasRehydrationInfo: (action: UnknownAction) => boolean
}

export const getEndpointDefinition = <
Definitions extends EndpointDefinitions,
EndpointName extends keyof Definitions,
>(
context: ApiContext<Definitions>,
endpointName: EndpointName,
) => context.endpointDefinitions[endpointName]

export type Api<
BaseQuery extends BaseQueryFn,
Definitions extends EndpointDefinitions,
Expand Down
21 changes: 17 additions & 4 deletions packages/toolkit/src/query/core/apiState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ export type InfiniteData<DataType, PageParam> = {
pageParams: Array<PageParam>
}

// NOTE: DO NOT import and use this for runtime comparisons internally,
// except in the RTKQ React package. Use the string versions just below this.
// ESBuild auto-inlines TS enums, which bloats our bundle with many repeated
// constants like "initialized":
// https://github.com/evanw/esbuild/releases/tag/v0.14.7
// We still have to use this in the React package since we don't publicly export
// the string constants below.
/**
* Strings describing the query state at any given time.
*/
Expand All @@ -75,6 +82,12 @@ export enum QueryStatus {
rejected = 'rejected',
}

// Use these string constants for runtime comparisons internally
export const STATUS_UNINITIALIZED = QueryStatus.uninitialized
export const STATUS_PENDING = QueryStatus.pending
export const STATUS_FULFILLED = QueryStatus.fulfilled
export const STATUS_REJECTED = QueryStatus.rejected

export type RequestStatusFlags =
| {
status: QueryStatus.uninitialized
Expand Down Expand Up @@ -108,10 +121,10 @@ export type RequestStatusFlags =
export function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags {
return {
status,
isUninitialized: status === QueryStatus.uninitialized,
isLoading: status === QueryStatus.pending,
isSuccess: status === QueryStatus.fulfilled,
isError: status === QueryStatus.rejected,
isUninitialized: status === STATUS_UNINITIALIZED,
isLoading: status === STATUS_PENDING,
isSuccess: status === STATUS_FULFILLED,
isError: status === STATUS_REJECTED,
} as any
}

Expand Down
7 changes: 4 additions & 3 deletions packages/toolkit/src/query/core/buildInitiate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import type {
} from '@reduxjs/toolkit'
import type { Dispatch } from 'redux'
import { asSafePromise } from '../../tsHelpers'
import type { Api, ApiContext } from '../apiTypes'
import { getEndpointDefinition, type Api, type ApiContext } from '../apiTypes'
import type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes'
import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
import {
ENDPOINT_QUERY,
isQueryDefinition,
type EndpointDefinition,
type EndpointDefinitions,
Expand Down Expand Up @@ -303,7 +304,7 @@ export function buildInitiate({

function getRunningQueryThunk(endpointName: string, queryArgs: any) {
return (dispatch: Dispatch) => {
const endpointDefinition = context.endpointDefinitions[endpointName]
const endpointDefinition = getEndpointDefinition(context, endpointName)
const queryCacheKey = serializeQueryArgs({
queryArgs,
endpointDefinition,
Expand Down Expand Up @@ -393,7 +394,7 @@ You must add the middleware for RTK-Query to function correctly!`,

const commonThunkArgs = {
...rest,
type: 'query' as const,
type: ENDPOINT_QUERY as 'query',
subscribe,
forceRefetch: forceRefetch,
subscriptionOptions,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getEndpointDefinition } from '@internal/query/apiTypes'
import type { QueryDefinition } from '../../endpointDefinitions'
import type { ConfigState, QueryCacheKey, QuerySubState } from '../apiState'
import { isAnyOf } from '../rtkImports'
Expand Down Expand Up @@ -155,9 +156,10 @@ export const buildCacheCollectionHandler: InternalHandlerBuilder = ({
api: SubMiddlewareApi,
config: ConfigState<string>,
) {
const endpointDefinition = context.endpointDefinitions[
endpointName
] as QueryDefinition<any, any, any, any>
const endpointDefinition = getEndpointDefinition(
context,
endpointName,
) as QueryDefinition<any, any, any, any>
const keepUnusedDataFor =
endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor

Expand Down
46 changes: 26 additions & 20 deletions packages/toolkit/src/query/core/buildMiddleware/cacheLifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import type {
PromiseWithKnownReason,
SubMiddlewareApi,
} from './types'
import { getEndpointDefinition } from '@internal/query/apiTypes'

export type ReferenceCacheLifecycle = never

Expand Down Expand Up @@ -205,6 +206,9 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({
}
const lifecycleMap: Record<string, CacheLifecycle> = {}

const { removeQueryResult, removeMutationResult, cacheEntriesUpserted } =
api.internalActions

function resolveLifecycleEntry(
cacheKey: string,
data: unknown,
Expand All @@ -229,6 +233,16 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({
}
}

function getActionMetaFields(
action:
| ReturnType<typeof queryThunk.pending>
| ReturnType<typeof mutationThunk.pending>,
) {
const { arg, requestId } = action.meta
const { endpointName, originalArgs } = arg
return [endpointName, originalArgs, requestId] as const
}

const handler: ApiMiddlewareInternalHandler = (
action,
mwApi,
Expand All @@ -250,13 +264,10 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({
}

if (queryThunk.pending.match(action)) {
checkForNewCacheKey(
action.meta.arg.endpointName,
cacheKey,
action.meta.requestId,
action.meta.arg.originalArgs,
)
} else if (api.internalActions.cacheEntriesUpserted.match(action)) {
const [endpointName, originalArgs, requestId] =
getActionMetaFields(action)
checkForNewCacheKey(endpointName, cacheKey, requestId, originalArgs)
} else if (cacheEntriesUpserted.match(action)) {
for (const { queryDescription, value } of action.payload) {
const { endpointName, originalArgs, queryCacheKey } = queryDescription
checkForNewCacheKey(
Expand All @@ -271,19 +282,15 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({
} else if (mutationThunk.pending.match(action)) {
const state = mwApi.getState()[reducerPath].mutations[cacheKey]
if (state) {
handleNewKey(
action.meta.arg.endpointName,
action.meta.arg.originalArgs,
cacheKey,
mwApi,
action.meta.requestId,
)
const [endpointName, originalArgs, requestId] =
getActionMetaFields(action)
handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId)
}
} else if (isFulfilledThunk(action)) {
resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta)
} else if (
api.internalActions.removeQueryResult.match(action) ||
api.internalActions.removeMutationResult.match(action)
removeQueryResult.match(action) ||
removeMutationResult.match(action)
) {
removeLifecycleEntry(cacheKey)
} else if (api.util.resetApiState.match(action)) {
Expand All @@ -298,9 +305,8 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({
if (isMutationThunk(action)) {
return action.meta.arg.fixedCacheKey ?? action.meta.requestId
}
if (api.internalActions.removeQueryResult.match(action))
return action.payload.queryCacheKey
if (api.internalActions.removeMutationResult.match(action))
if (removeQueryResult.match(action)) return action.payload.queryCacheKey
if (removeMutationResult.match(action))
return getMutationCacheKey(action.payload)
return ''
}
Expand All @@ -312,7 +318,7 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({
mwApi: SubMiddlewareApi,
requestId: string,
) {
const endpointDefinition = context.endpointDefinitions[endpointName]
const endpointDefinition = getEndpointDefinition(context, endpointName)
const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded
if (!onCacheEntryAdded) return

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import type {
} from '../../endpointDefinitions'
import { calculateProvidedBy } from '../../endpointDefinitions'
import type { CombinedState, QueryCacheKey } from '../apiState'
import { QueryStatus } from '../apiState'
import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'
import { calculateProvidedByThunk } from '../buildThunks'
import type {
SubMiddlewareApi,
Expand Down Expand Up @@ -127,7 +127,7 @@ export const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({
queryCacheKey: queryCacheKey as QueryCacheKey,
}),
)
} else if (querySubState.status !== QueryStatus.uninitialized) {
} else if (querySubState.status !== STATUS_UNINITIALIZED) {
mwApi.dispatch(refetchQuery(querySubState))
}
}
Expand Down
21 changes: 3 additions & 18 deletions packages/toolkit/src/query/core/buildMiddleware/polling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type {
Subscribers,
SubscribersInternal,
} from '../apiState'
import { QueryStatus } from '../apiState'
import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'
import type {
QueryStateMeta,
SubMiddlewareApi,
Expand Down Expand Up @@ -75,20 +75,6 @@ export const buildPollingHandler: InternalHandlerBuilder = ({
}
}

function getCacheEntrySubscriptions(
queryCacheKey: QueryCacheKey,
api: SubMiddlewareApi,
) {
const state = api.getState()[reducerPath]
const querySubState = state.queries[queryCacheKey]
const subscriptions = currentSubscriptions.get(queryCacheKey)

if (!querySubState || querySubState.status === QueryStatus.uninitialized)
return

return subscriptions
}

function startNextPoll(
{ queryCacheKey }: QuerySubstateIdentifier,
api: SubMiddlewareApi,
Expand All @@ -97,8 +83,7 @@ export const buildPollingHandler: InternalHandlerBuilder = ({
const querySubState = state.queries[queryCacheKey]
const subscriptions = currentSubscriptions.get(queryCacheKey)

if (!querySubState || querySubState.status === QueryStatus.uninitialized)
return
if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) return

const { lowestPollingInterval, skipPollingIfUnfocused } =
findLowestPollingInterval(subscriptions)
Expand Down Expand Up @@ -133,7 +118,7 @@ export const buildPollingHandler: InternalHandlerBuilder = ({
const querySubState = state.queries[queryCacheKey]
const subscriptions = currentSubscriptions.get(queryCacheKey)

if (!querySubState || querySubState.status === QueryStatus.uninitialized) {
if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {
return
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { getEndpointDefinition } from '@internal/query/apiTypes'
import type {
BaseQueryError,
BaseQueryFn,
BaseQueryMeta,
} from '../../baseQueryTypes'
import { DefinitionType, isAnyQueryDefinition } from '../../endpointDefinitions'
import { isAnyQueryDefinition } from '../../endpointDefinitions'
import type { Recipe } from '../buildThunks'
import { isFulfilled, isPending, isRejected } from '../rtkImports'
import type {
Expand Down Expand Up @@ -442,7 +443,7 @@ export const buildQueryLifecycleHandler: InternalHandlerBuilder = ({
requestId,
arg: { endpointName, originalArgs },
} = action.meta
const endpointDefinition = context.endpointDefinitions[endpointName]
const endpointDefinition = getEndpointDefinition(context, endpointName)
const onQueryStarted = endpointDefinition?.onQueryStarted
if (onQueryStarted) {
const lifecycle = {} as CacheLifecycle
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { QueryStatus } from '../apiState'
import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'
import type { QueryCacheKey } from '../apiState'
import { onFocus, onOnline } from '../setupListeners'
import type {
ApiMiddlewareInternalHandler,
InternalHandlerBuilder,
SubMiddlewareApi,
} from './types'
import { countObjectKeys } from '../../utils/countObjectKeys'

export const buildWindowEventHandler: InternalHandlerBuilder = ({
reducerPath,
Expand Down Expand Up @@ -53,7 +52,7 @@ export const buildWindowEventHandler: InternalHandlerBuilder = ({
queryCacheKey: queryCacheKey as QueryCacheKey,
}),
)
} else if (querySubState.status !== QueryStatus.uninitialized) {
} else if (querySubState.status !== STATUS_UNINITIALIZED) {
api.dispatch(refetchQuery(querySubState))
}
}
Expand Down
8 changes: 4 additions & 4 deletions packages/toolkit/src/query/core/buildSelectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ import type {
InfiniteQuerySubState,
MutationSubState,
QueryCacheKey,
QueryKeys,
QueryState,
QuerySubState,
RequestStatusFlags,
RootState as _RootState,
QueryStatus,
} from './apiState'
import { QueryStatus, getRequestStatusFlags } from './apiState'
import { STATUS_UNINITIALIZED, getRequestStatusFlags } from './apiState'
import { getMutationCacheKey } from './buildSlice'
import type { createSelector as _createSelector } from './rtkImports'
import { createNextState } from './rtkImports'
Expand Down Expand Up @@ -151,7 +151,7 @@ export type MutationResultSelectorResult<
> = MutationSubState<Definition> & RequestStatusFlags

const initialSubState: QuerySubState<any> = {
status: QueryStatus.uninitialized as const,
status: STATUS_UNINITIALIZED,
}

// abuse immer to freeze default states
Expand Down Expand Up @@ -388,7 +388,7 @@ export function buildSelectors<
{ status: QueryStatus.uninitialized }
> =>
entry?.endpointName === queryName &&
entry.status !== QueryStatus.uninitialized,
entry.status !== STATUS_UNINITIALIZED,
(entry) => entry.originalArgs,
)
}
Expand Down
Loading
Loading