Skip to content

Commit

Permalink
move data from payload and arg to meta
Browse files Browse the repository at this point in the history
`meta.arg.startedTimeStamp` -> `meta.startedTimeStamp`
`payload.fulfilledTimeStamp` -> `meta.fulfilledTimeStamp`
`payload.result` -> `payload`
  • Loading branch information
phryneas committed May 27, 2021
1 parent fc3491c commit c125c38
Show file tree
Hide file tree
Showing 9 changed files with 97 additions and 71 deletions.
31 changes: 12 additions & 19 deletions src/query/core/buildInitiate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ import {
QueryArgFrom,
ResultTypeFrom,
} from '../endpointDefinitions'
import type { QueryThunkArg, MutationThunkArg } from './buildThunks'
import type {
QueryThunkArg,
MutationThunkArg,
QueryThunk,
MutationThunk,
} from './buildThunks'
import {
AnyAction,
AsyncThunk,
Expand Down Expand Up @@ -108,10 +113,6 @@ export type MutationActionCreatorResult<
* Whether the mutation is being tracked in the store.
*/
track?: boolean
/**
* Timestamp for when the mutation was initiated
*/
startedTimeStamp: number
}
/**
* A unique string generated for the request sequence
Expand Down Expand Up @@ -186,8 +187,8 @@ export function buildInitiate({
api,
}: {
serializeQueryArgs: InternalSerializeQueryArgs
queryThunk: AsyncThunk<any, QueryThunkArg, {}>
mutationThunk: AsyncThunk<any, MutationThunkArg, {}>
queryThunk: QueryThunk
mutationThunk: MutationThunk
api: Api<any, EndpointDefinitions, any, any>
}) {
const {
Expand Down Expand Up @@ -217,7 +218,6 @@ export function buildInitiate({
endpointName,
originalArgs: arg,
queryCacheKey,
startedTimeStamp: Date.now(),
})
const thunkResult = dispatch(thunk)
const { requestId, abort } = thunkResult
Expand Down Expand Up @@ -266,30 +266,23 @@ export function buildInitiate({
endpointName: string,
definition: MutationDefinition<any, any, any, any>
): StartMutationActionCreator<any> {
return (arg, { track = true } = {}) => (dispatch, getState) => {
return (arg, { track = true } = {}) => (dispatch) => {
const thunk = mutationThunk({
endpointName,
originalArgs: arg,
track,
startedTimeStamp: Date.now(),
})
const thunkResult = dispatch(thunk)
const { requestId, abort } = thunkResult
const returnValuePromise = thunkResult
.then(unwrapResult)
.then((unwrapped) => ({
data: unwrapped.result,
}))
.unwrap()
.then((data) => ({ data }))
.catch((error) => ({ error }))
return Object.assign(returnValuePromise, {
arg: thunkResult.arg,
requestId,
abort,
unwrap() {
return thunkResult
.then(unwrapResult)
.then((unwrapped) => unwrapped.result)
},
unwrap: thunkResult.unwrap,
unsubscribe() {
if (track) dispatch(unsubscribeMutationResult({ requestId }))
},
Expand Down
2 changes: 1 addition & 1 deletion src/query/core/buildMiddleware/cacheLifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ export const build: SubMiddlewareBuilder = ({
} else if (isFullfilledThunk(action)) {
const lifecycle = lifecycleMap[cacheKey]
if (lifecycle?.valueResolved) {
lifecycle.valueResolved({ data: action.payload.result })
lifecycle.valueResolved({ data: action.payload })
delete lifecycle.valueResolved
}
} else if (
Expand Down
1 change: 0 additions & 1 deletion src/query/core/buildMiddleware/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ export function buildMiddleware<
originalArgs: querySubState.originalArgs,
subscribe: false,
forceRefetch: true,
startedTimeStamp: Date.now(),
queryCacheKey: queryCacheKey as any,
...override,
})
Expand Down
2 changes: 1 addition & 1 deletion src/query/core/buildMiddleware/queryLifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ export const build: SubMiddlewareBuilder = ({
}
} else if (isFullfilledThunk(action)) {
const { requestId } = action.meta
lifecycleMap[requestId]?.resolve({ data: action.payload.result })
lifecycleMap[requestId]?.resolve({ data: action.payload })
delete lifecycleMap[requestId]
} else if (isRejectedThunk(action)) {
const { requestId, rejectedWithValue } = action.meta
Expand Down
11 changes: 8 additions & 3 deletions src/query/core/buildMiddleware/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ import {
import { Api, ApiContext } from '../../apiTypes'
import { AssertTagTypes, EndpointDefinitions } from '../../endpointDefinitions'
import { QueryStatus, QuerySubState, RootState } from '../apiState'
import { MutationThunkArg, QueryThunkArg, ThunkResult } from '../buildThunks'
import {
MutationThunk,
QueryThunk,
QueryThunkArg,
ThunkResult,
} from '../buildThunks'

export type QueryStateMeta<T> = Record<string, undefined | T>
export type TimeoutId = ReturnType<typeof setTimeout>
Expand All @@ -22,8 +27,8 @@ export interface BuildMiddlewareInput<
> {
reducerPath: ReducerPath
context: ApiContext<Definitions>
queryThunk: AsyncThunk<ThunkResult, QueryThunkArg, {}>
mutationThunk: AsyncThunk<ThunkResult, MutationThunkArg, {}>
queryThunk: QueryThunk
mutationThunk: MutationThunk
api: Api<any, Definitions, ReducerPath, TagTypes>
assertTagType: AssertTagTypes
}
Expand Down
43 changes: 27 additions & 16 deletions src/query/core/buildSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,22 @@ export function buildSlice({
config,
}: {
reducerPath: string
queryThunk: AsyncThunk<ThunkResult, QueryThunkArg, {}>
mutationThunk: AsyncThunk<ThunkResult, MutationThunkArg, {}>
queryThunk: AsyncThunk<
ThunkResult,
QueryThunkArg,
{
pendingMeta: { startedTimeStamp: number }
fulfilledMeta: { fulfilledTimeStamp: number }
}
>
mutationThunk: AsyncThunk<
ThunkResult,
MutationThunkArg,
{
pendingMeta: { startedTimeStamp: number }
fulfilledMeta: { fulfilledTimeStamp: number }
}
>
context: ApiContext<EndpointDefinitions>
assertTagType: AssertTagTypes
config: Omit<ConfigState<string>, 'online' | 'focused'>
Expand Down Expand Up @@ -108,7 +122,7 @@ export function buildSlice({
},
extraReducers(builder) {
builder
.addCase(queryThunk.pending, (draft, { meta: { arg, requestId } }) => {
.addCase(queryThunk.pending, (draft, { meta, meta: { arg } }) => {
if (arg.subscribe) {
// only initialize substate if we want to subscribe to it
draft[arg.queryCacheKey] ??= {
Expand All @@ -119,9 +133,9 @@ export function buildSlice({

updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
substate.status = QueryStatus.pending
substate.requestId = requestId
substate.requestId = meta.requestId
substate.originalArgs = arg.originalArgs
substate.startedTimeStamp = arg.startedTimeStamp
substate.startedTimeStamp = meta.startedTimeStamp
})
})
.addCase(queryThunk.fulfilled, (draft, { meta, payload }) => {
Expand All @@ -131,12 +145,9 @@ export function buildSlice({
(substate) => {
if (substate.requestId !== meta.requestId) return
substate.status = QueryStatus.fulfilled
substate.data = copyWithStructuralSharing(
substate.data,
payload.result
)
substate.data = copyWithStructuralSharing(substate.data, payload)
delete substate.error
substate.fulfilledTimeStamp = payload.fulfilledTimeStamp
substate.fulfilledTimeStamp = meta.fulfilledTimeStamp
}
)
})
Expand Down Expand Up @@ -178,26 +189,26 @@ export function buildSlice({
builder
.addCase(
mutationThunk.pending,
(draft, { meta: { arg, requestId } }) => {
(draft, { meta: { arg, requestId, startedTimeStamp } }) => {
if (!arg.track) return

draft[requestId] = {
status: QueryStatus.pending,
originalArgs: arg.originalArgs,
endpointName: arg.endpointName,
startedTimeStamp: arg.startedTimeStamp,
startedTimeStamp,
}
}
)
.addCase(
mutationThunk.fulfilled,
(draft, { payload, meta: { requestId, arg } }) => {
if (!arg.track) return
(draft, { payload, meta, meta: { requestId } }) => {
if (!meta.arg.track) return

updateMutationSubstateIfExists(draft, { requestId }, (substate) => {
substate.status = QueryStatus.fulfilled
substate.data = payload.result
substate.fulfilledTimeStamp = payload.fulfilledTimeStamp
substate.data = payload
substate.fulfilledTimeStamp = meta.fulfilledTimeStamp
})
}
)
Expand Down
73 changes: 46 additions & 27 deletions src/query/core/buildThunks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,42 +63,42 @@ declare module './module' {
}

type EndpointThunk<
Thunk extends AsyncThunk<any, any, any>,
Thunk extends QueryThunk | MutationThunk,
Definition extends EndpointDefinition<any, any, any, any>
> = Definition extends EndpointDefinition<
infer QueryArg,
infer BaseQueryFn,
any,
infer ResultType
>
? Thunk extends AsyncThunk<infer ATResult, infer ATArg, infer ATConfig>
? Thunk extends AsyncThunk<unknown, infer ATArg, infer ATConfig>
? AsyncThunk<
ATResult & { result: ResultType },
ResultType,
ATArg & { originalArgs: QueryArg },
ATConfig & { rejectValue: BaseQueryError<BaseQueryFn> }
>
: never
: never

export type PendingAction<
Thunk extends AsyncThunk<any, any, any>,
Thunk extends QueryThunk | MutationThunk,
Definition extends EndpointDefinition<any, any, any, any>
> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>

export type FulfilledAction<
Thunk extends AsyncThunk<any, any, any>,
Thunk extends QueryThunk | MutationThunk,
Definition extends EndpointDefinition<any, any, any, any>
> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>

export type RejectedAction<
Thunk extends AsyncThunk<any, any, any>,
Thunk extends QueryThunk | MutationThunk,
Definition extends EndpointDefinition<any, any, any, any>
> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>

export type Matcher<M> = (value: any) => value is M

export interface Matchers<
Thunk extends AsyncThunk<any, any, any>,
Thunk extends QueryThunk | MutationThunk,
Definition extends EndpointDefinition<any, any, any, any>
> {
matchPending: Matcher<PendingAction<Thunk, Definition>>
Expand All @@ -111,23 +111,30 @@ export interface QueryThunkArg
StartQueryActionCreatorOptions {
originalArgs: unknown
endpointName: string
startedTimeStamp: number
}

export interface MutationThunkArg {
originalArgs: unknown
endpointName: string
track?: boolean
startedTimeStamp: number
}

export interface ThunkResult {
fulfilledTimeStamp: number
result: unknown
}
export type ThunkResult = unknown

export type QueryThunk = AsyncThunk<ThunkResult, QueryThunkArg, {}>
export type MutationThunk = AsyncThunk<ThunkResult, MutationThunkArg, {}>
export type ThunkApiMetaConfig = {
pendingMeta: { startedTimeStamp: number }
fulfilledMeta: { fulfilledTimeStamp: number }
}
export type QueryThunk = AsyncThunk<
ThunkResult,
QueryThunkArg,
ThunkApiMetaConfig
>
export type MutationThunk = AsyncThunk<
ThunkResult,
MutationThunkArg,
ThunkApiMetaConfig
>

function defaultTransformResponse(baseQueryReturnValue: unknown) {
return baseQueryReturnValue
Expand Down Expand Up @@ -256,8 +263,11 @@ export function buildThunks<
const executeEndpoint: AsyncThunkPayloadCreator<
ThunkResult,
QueryThunkArg | MutationThunkArg,
{ state: RootState<any, string, ReducerPath> }
> = async (arg, { signal, rejectWithValue, dispatch, getState }) => {
ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }
> = async (
arg,
{ signal, rejectWithValue, fulfillWithValue, dispatch, getState }
) => {
const endpointDefinition = endpointDefinitions[arg.endpointName]

try {
Expand Down Expand Up @@ -292,10 +302,12 @@ export function buildThunks<
}
if (result.error) throw new HandledError(result.error, result.meta)

return {
fulfilledTimeStamp: Date.now(),
result: await transformResponse(result.data, result.meta),
}
return fulfillWithValue(
await transformResponse(result.data, result.meta),
{
fulfilledTimeStamp: Date.now(),
}
)
} catch (error) {
if (error instanceof HandledError) {
return rejectWithValue(error.value)
Expand All @@ -307,8 +319,11 @@ export function buildThunks<
const queryThunk = createAsyncThunk<
ThunkResult,
QueryThunkArg,
{ state: RootState<any, string, ReducerPath> }
ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }
>(`${reducerPath}/executeQuery`, executeEndpoint, {
getPendingMeta() {
return { startedTimeStamp: Date.now() }
},
condition(arg, { getState }) {
const state = getState()[reducerPath]
const requestState = state?.queries?.[arg.queryCacheKey]
Expand Down Expand Up @@ -342,8 +357,12 @@ export function buildThunks<
const mutationThunk = createAsyncThunk<
ThunkResult,
MutationThunkArg,
{ state: RootState<any, string, ReducerPath> }
>(`${reducerPath}/executeMutation`, executeEndpoint)
ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }
>(`${reducerPath}/executeMutation`, executeEndpoint, {
getPendingMeta() {
return { startedTimeStamp: Date.now() }
},
})

const hasTheForce = (options: any): options is { force: boolean } =>
'force' in options
Expand Down Expand Up @@ -399,8 +418,8 @@ export function buildThunks<

function buildMatchThunkActions<
Thunk extends
| AsyncThunk<any, QueryThunkArg, any>
| AsyncThunk<any, MutationThunkArg, any>
| AsyncThunk<any, QueryThunkArg, ThunkApiMetaConfig>
| AsyncThunk<any, MutationThunkArg, ThunkApiMetaConfig>
>(thunk: Thunk, endpointName: string) {
return {
matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),
Expand Down Expand Up @@ -432,7 +451,7 @@ export function calculateProvidedByThunk(
) {
return calculateProvidedBy(
endpointDefinitions[action.meta.arg.endpointName][type],
isFulfilled(action) ? action.payload.result : undefined,
isFulfilled(action) ? action.payload : undefined,
isRejectedWithValue(action) ? action.payload : undefined,
action.meta.arg.originalArgs,
assertTagType
Expand Down
1 change: 0 additions & 1 deletion src/query/tests/buildHooks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -850,7 +850,6 @@ describe('hooks tests', () => {
endpointName: string
originalArgs: { name: string }
track?: boolean
startedTimeStamp: number
}>(res.arg)
expectType<string>(res.requestId)
expectType<() => void>(res.abort)
Expand Down
Loading

0 comments on commit c125c38

Please sign in to comment.