-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
createAsyncThunk.ts
746 lines (695 loc) · 20.3 KB
/
createAsyncThunk.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
import type { Dispatch, UnknownAction } from 'redux'
import type { ThunkDispatch } from 'redux-thunk'
import type { ActionCreatorWithPreparedPayload } from './createAction'
import { createAction } from './createAction'
import { isAnyOf } from './matchers'
import { nanoid } from './nanoid'
import type {
FallbackIfUnknown,
Id,
IsAny,
IsUnknown,
SafePromise,
} from './tsHelpers'
export type BaseThunkAPI<
S,
E,
D extends Dispatch = Dispatch,
RejectedValue = unknown,
RejectedMeta = unknown,
FulfilledMeta = unknown,
> = {
dispatch: D
getState: () => S
extra: E
requestId: string
signal: AbortSignal
abort: (reason?: string) => void
rejectWithValue: IsUnknown<
RejectedMeta,
(value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>,
(
value: RejectedValue,
meta: RejectedMeta,
) => RejectWithValue<RejectedValue, RejectedMeta>
>
fulfillWithValue: IsUnknown<
FulfilledMeta,
<FulfilledValue>(value: FulfilledValue) => FulfilledValue,
<FulfilledValue>(
value: FulfilledValue,
meta: FulfilledMeta,
) => FulfillWithMeta<FulfilledValue, FulfilledMeta>
>
}
/**
* @public
*/
export interface SerializedError {
name?: string
message?: string
stack?: string
code?: string
}
const commonProperties: Array<keyof SerializedError> = [
'name',
'message',
'stack',
'code',
]
class RejectWithValue<Payload, RejectedMeta> {
/*
type-only property to distinguish between RejectWithValue and FulfillWithMeta
does not exist at runtime
*/
private readonly _type!: 'RejectWithValue'
constructor(
public readonly payload: Payload,
public readonly meta: RejectedMeta,
) {}
}
class FulfillWithMeta<Payload, FulfilledMeta> {
/*
type-only property to distinguish between RejectWithValue and FulfillWithMeta
does not exist at runtime
*/
private readonly _type!: 'FulfillWithMeta'
constructor(
public readonly payload: Payload,
public readonly meta: FulfilledMeta,
) {}
}
/**
* Serializes an error into a plain object.
* Reworked from https://github.com/sindresorhus/serialize-error
*
* @public
*/
export const miniSerializeError = (value: any): SerializedError => {
if (typeof value === 'object' && value !== null) {
const simpleError: SerializedError = {}
for (const property of commonProperties) {
if (typeof value[property] === 'string') {
simpleError[property] = value[property]
}
}
return simpleError
}
return { message: String(value) }
}
export type AsyncThunkConfig = {
state?: unknown
dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>
extra?: unknown
rejectValue?: unknown
serializedErrorType?: unknown
pendingMeta?: unknown
fulfilledMeta?: unknown
rejectedMeta?: unknown
}
export type GetState<ThunkApiConfig> = ThunkApiConfig extends {
state: infer State
}
? State
: unknown
type GetExtra<ThunkApiConfig> = ThunkApiConfig extends { extra: infer Extra }
? Extra
: unknown
type GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {
dispatch: infer Dispatch
}
? FallbackIfUnknown<
Dispatch,
ThunkDispatch<
GetState<ThunkApiConfig>,
GetExtra<ThunkApiConfig>,
UnknownAction
>
>
: ThunkDispatch<
GetState<ThunkApiConfig>,
GetExtra<ThunkApiConfig>,
UnknownAction
>
export type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<
GetState<ThunkApiConfig>,
GetExtra<ThunkApiConfig>,
GetDispatch<ThunkApiConfig>,
GetRejectValue<ThunkApiConfig>,
GetRejectedMeta<ThunkApiConfig>,
GetFulfilledMeta<ThunkApiConfig>
>
type GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {
rejectValue: infer RejectValue
}
? RejectValue
: unknown
type GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {
pendingMeta: infer PendingMeta
}
? PendingMeta
: unknown
type GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {
fulfilledMeta: infer FulfilledMeta
}
? FulfilledMeta
: unknown
type GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {
rejectedMeta: infer RejectedMeta
}
? RejectedMeta
: unknown
type GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {
serializedErrorType: infer GetSerializedErrorType
}
? GetSerializedErrorType
: SerializedError
type MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never)
/**
* A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.
* Might be useful for wrapping `createAsyncThunk` in custom abstractions.
*
* @public
*/
export type AsyncThunkPayloadCreatorReturnValue<
Returned,
ThunkApiConfig extends AsyncThunkConfig,
> = MaybePromise<
| IsUnknown<
GetFulfilledMeta<ThunkApiConfig>,
Returned,
FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>
>
| RejectWithValue<
GetRejectValue<ThunkApiConfig>,
GetRejectedMeta<ThunkApiConfig>
>
>
/**
* A type describing the `payloadCreator` argument to `createAsyncThunk`.
* Might be useful for wrapping `createAsyncThunk` in custom abstractions.
*
* @public
*/
export type AsyncThunkPayloadCreator<
Returned,
ThunkArg = void,
ThunkApiConfig extends AsyncThunkConfig = {},
> = (
arg: ThunkArg,
thunkAPI: GetThunkAPI<ThunkApiConfig>,
) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>
/**
* A ThunkAction created by `createAsyncThunk`.
* Dispatching it returns a Promise for either a
* fulfilled or rejected action.
* Also, the returned value contains an `abort()` method
* that allows the asyncAction to be cancelled from the outside.
*
* @public
*/
export type AsyncThunkAction<
Returned,
ThunkArg,
ThunkApiConfig extends AsyncThunkConfig,
> = (
dispatch: NonNullable<GetDispatch<ThunkApiConfig>>,
getState: () => GetState<ThunkApiConfig>,
extra: GetExtra<ThunkApiConfig>,
) => SafePromise<
| ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>>
| ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>
> & {
abort: (reason?: string) => void
requestId: string
arg: ThunkArg
unwrap: () => Promise<Returned>
}
type AsyncThunkActionCreator<
Returned,
ThunkArg,
ThunkApiConfig extends AsyncThunkConfig,
> = IsAny<
ThunkArg,
// any handling
(arg: ThunkArg) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,
// unknown handling
unknown extends ThunkArg
? (arg: ThunkArg) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument not specified or specified as void or undefined
: [ThunkArg] extends [void] | [undefined]
? () => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains void
: [void] extends [ThunkArg] // make optional
? (
arg?: ThunkArg,
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains undefined
: [undefined] extends [ThunkArg]
? WithStrictNullChecks<
// with strict nullChecks: make optional
(
arg?: ThunkArg,
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,
// without strict null checks this will match everything, so don't make it optional
(
arg: ThunkArg,
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>
> // default case: normal argument
: (
arg: ThunkArg,
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>
>
/**
* Options object for `createAsyncThunk`.
*
* @public
*/
export type AsyncThunkOptions<
ThunkArg = void,
ThunkApiConfig extends AsyncThunkConfig = {},
> = {
/**
* A method to control whether the asyncThunk should be executed. Has access to the
* `arg`, `api.getState()` and `api.extra` arguments.
*
* @returns `false` if it should be skipped
*/
condition?(
arg: ThunkArg,
api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
): MaybePromise<boolean | undefined>
/**
* If `condition` returns `false`, the asyncThunk will be skipped.
* This option allows you to control whether a `rejected` action with `meta.condition == false`
* will be dispatched or not.
*
* @default `false`
*/
dispatchConditionRejection?: boolean
serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>
/**
* A function to use when generating the `requestId` for the request sequence.
*
* @default `nanoid`
*/
idGenerator?: (arg: ThunkArg) => string
} & IsUnknown<
GetPendingMeta<ThunkApiConfig>,
{
/**
* A method to generate additional properties to be added to `meta` of the pending action.
*
* Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.
* Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload
*/
getPendingMeta?(
base: {
arg: ThunkArg
requestId: string
},
api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
): GetPendingMeta<ThunkApiConfig>
},
{
/**
* A method to generate additional properties to be added to `meta` of the pending action.
*/
getPendingMeta(
base: {
arg: ThunkArg
requestId: string
},
api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
): GetPendingMeta<ThunkApiConfig>
}
>
export type AsyncThunkPendingActionCreator<
ThunkArg,
ThunkApiConfig = {},
> = ActionCreatorWithPreparedPayload<
[string, ThunkArg, GetPendingMeta<ThunkApiConfig>?],
undefined,
string,
never,
{
arg: ThunkArg
requestId: string
requestStatus: 'pending'
} & GetPendingMeta<ThunkApiConfig>
>
export type AsyncThunkRejectedActionCreator<
ThunkArg,
ThunkApiConfig = {},
> = ActionCreatorWithPreparedPayload<
[
Error | null,
string,
ThunkArg,
GetRejectValue<ThunkApiConfig>?,
GetRejectedMeta<ThunkApiConfig>?,
],
GetRejectValue<ThunkApiConfig> | undefined,
string,
GetSerializedErrorType<ThunkApiConfig>,
{
arg: ThunkArg
requestId: string
requestStatus: 'rejected'
aborted: boolean
condition: boolean
} & (
| ({ rejectedWithValue: false } & {
[K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined
})
| ({ rejectedWithValue: true } & GetRejectedMeta<ThunkApiConfig>)
)
>
export type AsyncThunkFulfilledActionCreator<
Returned,
ThunkArg,
ThunkApiConfig = {},
> = ActionCreatorWithPreparedPayload<
[Returned, string, ThunkArg, GetFulfilledMeta<ThunkApiConfig>?],
Returned,
string,
never,
{
arg: ThunkArg
requestId: string
requestStatus: 'fulfilled'
} & GetFulfilledMeta<ThunkApiConfig>
>
/**
* A type describing the return value of `createAsyncThunk`.
* Might be useful for wrapping `createAsyncThunk` in custom abstractions.
*
* @public
*/
export type AsyncThunk<
Returned,
ThunkArg,
ThunkApiConfig extends AsyncThunkConfig,
> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {
pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>
rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>
fulfilled: AsyncThunkFulfilledActionCreator<
Returned,
ThunkArg,
ThunkApiConfig
>
// matchSettled?
settled: (
action: any,
) => action is ReturnType<
| AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>
| AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>
>
typePrefix: string
}
export type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<
NewConfig & Omit<OldConfig, keyof NewConfig>
>
type CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> = {
/**
*
* @param typePrefix
* @param payloadCreator
* @param options
*
* @public
*/
// separate signature without `AsyncThunkConfig` for better inference
<Returned, ThunkArg = void>(
typePrefix: string,
payloadCreator: AsyncThunkPayloadCreator<
Returned,
ThunkArg,
CurriedThunkApiConfig
>,
options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>,
): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>
/**
*
* @param typePrefix
* @param payloadCreator
* @param options
*
* @public
*/
<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(
typePrefix: string,
payloadCreator: AsyncThunkPayloadCreator<
Returned,
ThunkArg,
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
>,
options?: AsyncThunkOptions<
ThunkArg,
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
>,
): AsyncThunk<
Returned,
ThunkArg,
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
>
withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
>
}
export const createAsyncThunk = /* @__PURE__ */ (() => {
function createAsyncThunk<
Returned,
ThunkArg,
ThunkApiConfig extends AsyncThunkConfig,
>(
typePrefix: string,
payloadCreator: AsyncThunkPayloadCreator<
Returned,
ThunkArg,
ThunkApiConfig
>,
options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>,
): AsyncThunk<Returned, ThunkArg, ThunkApiConfig> {
type RejectedValue = GetRejectValue<ThunkApiConfig>
type PendingMeta = GetPendingMeta<ThunkApiConfig>
type FulfilledMeta = GetFulfilledMeta<ThunkApiConfig>
type RejectedMeta = GetRejectedMeta<ThunkApiConfig>
const fulfilled: AsyncThunkFulfilledActionCreator<
Returned,
ThunkArg,
ThunkApiConfig
> = createAction(
typePrefix + '/fulfilled',
(
payload: Returned,
requestId: string,
arg: ThunkArg,
meta?: FulfilledMeta,
) => ({
payload,
meta: {
...((meta as any) || {}),
arg,
requestId,
requestStatus: 'fulfilled' as const,
},
}),
)
const pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig> =
createAction(
typePrefix + '/pending',
(requestId: string, arg: ThunkArg, meta?: PendingMeta) => ({
payload: undefined,
meta: {
...((meta as any) || {}),
arg,
requestId,
requestStatus: 'pending' as const,
},
}),
)
const rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> =
createAction(
typePrefix + '/rejected',
(
error: Error | null,
requestId: string,
arg: ThunkArg,
payload?: RejectedValue,
meta?: RejectedMeta,
) => ({
payload,
error: ((options && options.serializeError) || miniSerializeError)(
error || 'Rejected',
) as GetSerializedErrorType<ThunkApiConfig>,
meta: {
...((meta as any) || {}),
arg,
requestId,
rejectedWithValue: !!payload,
requestStatus: 'rejected' as const,
aborted: error?.name === 'AbortError',
condition: error?.name === 'ConditionError',
},
}),
)
function actionCreator(
arg: ThunkArg,
): AsyncThunkAction<Returned, ThunkArg, Required<ThunkApiConfig>> {
return (dispatch, getState, extra) => {
const requestId = options?.idGenerator
? options.idGenerator(arg)
: nanoid()
const abortController = new AbortController()
let abortHandler: (() => void) | undefined
let abortReason: string | undefined
function abort(reason?: string) {
abortReason = reason
abortController.abort()
}
const promise = (async function () {
let finalAction: ReturnType<typeof fulfilled | typeof rejected>
try {
let conditionResult = options?.condition?.(arg, { getState, extra })
if (isThenable(conditionResult)) {
conditionResult = await conditionResult
}
if (conditionResult === false || abortController.signal.aborted) {
// eslint-disable-next-line no-throw-literal
throw {
name: 'ConditionError',
message: 'Aborted due to condition callback returning false.',
}
}
const abortedPromise = new Promise<never>((_, reject) => {
abortHandler = () => {
reject({
name: 'AbortError',
message: abortReason || 'Aborted',
})
}
abortController.signal.addEventListener('abort', abortHandler)
})
dispatch(
pending(
requestId,
arg,
options?.getPendingMeta?.(
{ requestId, arg },
{ getState, extra },
),
) as any,
)
finalAction = await Promise.race([
abortedPromise,
Promise.resolve(
payloadCreator(arg, {
dispatch,
getState,
extra,
requestId,
signal: abortController.signal,
abort,
rejectWithValue: ((
value: RejectedValue,
meta?: RejectedMeta,
) => {
return new RejectWithValue(value, meta)
}) as any,
fulfillWithValue: ((value: unknown, meta?: FulfilledMeta) => {
return new FulfillWithMeta(value, meta)
}) as any,
}),
).then((result) => {
if (result instanceof RejectWithValue) {
throw result
}
if (result instanceof FulfillWithMeta) {
return fulfilled(result.payload, requestId, arg, result.meta)
}
return fulfilled(result as any, requestId, arg)
}),
])
} catch (err) {
finalAction =
err instanceof RejectWithValue
? rejected(null, requestId, arg, err.payload, err.meta)
: rejected(err as any, requestId, arg)
} finally {
if (abortHandler) {
abortController.signal.removeEventListener('abort', abortHandler)
}
}
// We dispatch the result action _after_ the catch, to avoid having any errors
// here get swallowed by the try/catch block,
// per https://twitter.com/dan_abramov/status/770914221638942720
// and https://github.com/reduxjs/redux-toolkit/blob/e85eb17b39a2118d859f7b7746e0f3fee523e089/docs/tutorials/advanced-tutorial.md#async-error-handling-logic-in-thunks
const skipDispatch =
options &&
!options.dispatchConditionRejection &&
rejected.match(finalAction) &&
(finalAction as any).meta.condition
if (!skipDispatch) {
dispatch(finalAction as any)
}
return finalAction
})()
return Object.assign(promise as SafePromise<any>, {
abort,
requestId,
arg,
unwrap() {
return promise.then<any>(unwrapResult)
},
})
}
}
return Object.assign(
actionCreator as AsyncThunkActionCreator<
Returned,
ThunkArg,
ThunkApiConfig
>,
{
pending,
rejected,
fulfilled,
settled: isAnyOf(rejected, fulfilled),
typePrefix,
},
)
}
createAsyncThunk.withTypes = () => createAsyncThunk
return createAsyncThunk as CreateAsyncThunk<AsyncThunkConfig>
})()
interface UnwrappableAction {
payload: any
meta?: any
error?: any
}
type UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<
T,
{ error: any }
>['payload']
/**
* @public
*/
export function unwrapResult<R extends UnwrappableAction>(
action: R,
): UnwrappedActionPayload<R> {
if (action.meta && action.meta.rejectedWithValue) {
throw action.payload
}
if (action.error) {
throw action.error
}
return action.payload
}
type WithStrictNullChecks<True, False> = undefined extends boolean
? False
: True
function isThenable(value: any): value is PromiseLike<any> {
return (
value !== null &&
typeof value === 'object' &&
typeof value.then === 'function'
)
}