|
| 1 | +import { computed, DestroyRef, inject, Injector, signal } from '@angular/core'; |
| 2 | +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; |
| 3 | +import { |
| 4 | + catchError, |
| 5 | + defer, |
| 6 | + EMPTY, |
| 7 | + finalize, |
| 8 | + Observable, |
| 9 | + Subject, |
| 10 | + tap, |
| 11 | +} from 'rxjs'; |
| 12 | + |
| 13 | +import { concatOp, FlatteningOperator } from './flattening-operator'; |
| 14 | +import { Mutation, MutationResult, MutationStatus } from './with-mutations'; |
| 15 | + |
| 16 | +export type Func<P, R> = (params: P) => R; |
| 17 | + |
| 18 | +export interface RxMutationOptions<P, R> { |
| 19 | + operation: Func<P, Observable<R>>; |
| 20 | + onSuccess?: (result: R, params: P) => void; |
| 21 | + onError?: (error: unknown, params: P) => void; |
| 22 | + operator?: FlatteningOperator; |
| 23 | + injector?: Injector; |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * Creates a mutation that leverages RxJS. |
| 28 | + * |
| 29 | + * For each mutation the following options can be defined: |
| 30 | + * - `operation`: A function that defines the mutation logic. It returns an Observable. |
| 31 | + * - `onSuccess`: A callback that is called when the mutation is successful. |
| 32 | + * - `onError`: A callback that is called when the mutation fails. |
| 33 | + * - `operator`: An optional wrapper of an RxJS flattening operator. By default `concat` sematics are used. |
| 34 | + * - `injector`: An optional Angular injector to use for dependency injection. |
| 35 | + * |
| 36 | + * The `operation` is the only mandatory option. |
| 37 | + * |
| 38 | + * ```typescript |
| 39 | + * export type Params = { |
| 40 | + * value: number; |
| 41 | + * }; |
| 42 | + * |
| 43 | + * export const CounterStore = signalStore( |
| 44 | + * { providedIn: 'root' }, |
| 45 | + * withState({ counter: 0 }), |
| 46 | + * withMutations((store) => ({ |
| 47 | + * increment: rxMutation({ |
| 48 | + * operation: (params: Params) => { |
| 49 | + * return calcSum(store.counter(), params.value); |
| 50 | + * }, |
| 51 | + * operator: concatOp, |
| 52 | + * onSuccess: (result) => { |
| 53 | + * console.log('result', result); |
| 54 | + * patchState(store, { counter: result }); |
| 55 | + * }, |
| 56 | + * onError: (error) => { |
| 57 | + * console.error('Error occurred:', error); |
| 58 | + * }, |
| 59 | + * }), |
| 60 | + * })), |
| 61 | + * ); |
| 62 | + * |
| 63 | + * function calcSum(a: number, b: number): Observable<number> { |
| 64 | + * return of(a + b); |
| 65 | + * } |
| 66 | + * ``` |
| 67 | + * |
| 68 | + * @param options |
| 69 | + * @returns |
| 70 | + */ |
| 71 | +export function rxMutation<P, R>( |
| 72 | + options: RxMutationOptions<P, R>, |
| 73 | +): Mutation<P, R> { |
| 74 | + const inputSubject = new Subject<{ |
| 75 | + param: P; |
| 76 | + resolve: (result: MutationResult<R>) => void; |
| 77 | + }>(); |
| 78 | + const flatteningOp = options.operator ?? concatOp; |
| 79 | + |
| 80 | + const destroyRef = options.injector?.get(DestroyRef) ?? inject(DestroyRef); |
| 81 | + |
| 82 | + const callCount = signal(0); |
| 83 | + const errorSignal = signal<unknown>(undefined); |
| 84 | + const idle = signal(true); |
| 85 | + const isPending = computed(() => callCount() > 0); |
| 86 | + |
| 87 | + const status = computed<MutationStatus>(() => { |
| 88 | + if (idle()) { |
| 89 | + return 'idle'; |
| 90 | + } |
| 91 | + if (callCount() > 0) { |
| 92 | + return 'pending'; |
| 93 | + } |
| 94 | + if (errorSignal()) { |
| 95 | + return 'error'; |
| 96 | + } |
| 97 | + return 'success'; |
| 98 | + }); |
| 99 | + |
| 100 | + const initialInnerStatus: MutationStatus = 'idle'; |
| 101 | + let innerStatus: MutationStatus = initialInnerStatus; |
| 102 | + let lastResult: R; |
| 103 | + |
| 104 | + inputSubject |
| 105 | + .pipe( |
| 106 | + flatteningOp.rxJsOperator((input) => |
| 107 | + defer(() => { |
| 108 | + callCount.update((c) => c + 1); |
| 109 | + idle.set(false); |
| 110 | + return options.operation(input.param).pipe( |
| 111 | + tap((result: R) => { |
| 112 | + options.onSuccess?.(result, input.param); |
| 113 | + innerStatus = 'success'; |
| 114 | + errorSignal.set(undefined); |
| 115 | + lastResult = result; |
| 116 | + }), |
| 117 | + catchError((error: unknown) => { |
| 118 | + options.onError?.(error, input.param); |
| 119 | + errorSignal.set(error); |
| 120 | + innerStatus = 'error'; |
| 121 | + return EMPTY; |
| 122 | + }), |
| 123 | + finalize(() => { |
| 124 | + callCount.update((c) => c - 1); |
| 125 | + |
| 126 | + if (innerStatus === 'success') { |
| 127 | + input.resolve({ |
| 128 | + status: 'success', |
| 129 | + value: lastResult, |
| 130 | + }); |
| 131 | + } else if (innerStatus === 'error') { |
| 132 | + input.resolve({ |
| 133 | + status: 'error', |
| 134 | + error: errorSignal(), |
| 135 | + }); |
| 136 | + } else { |
| 137 | + input.resolve({ |
| 138 | + status: 'aborted', |
| 139 | + }); |
| 140 | + } |
| 141 | + |
| 142 | + innerStatus = initialInnerStatus; |
| 143 | + }), |
| 144 | + ); |
| 145 | + }), |
| 146 | + ), |
| 147 | + takeUntilDestroyed(destroyRef), |
| 148 | + ) |
| 149 | + .subscribe(); |
| 150 | + |
| 151 | + const mutationFn = (param: P) => { |
| 152 | + return new Promise<MutationResult<R>>((resolve) => { |
| 153 | + if (callCount() > 0 && flatteningOp.exhaustSemantics) { |
| 154 | + resolve({ |
| 155 | + status: 'aborted', |
| 156 | + }); |
| 157 | + } else { |
| 158 | + inputSubject.next({ |
| 159 | + param, |
| 160 | + resolve, |
| 161 | + }); |
| 162 | + } |
| 163 | + }); |
| 164 | + }; |
| 165 | + |
| 166 | + const mutation = mutationFn as Mutation<P, R>; |
| 167 | + mutation.status = status; |
| 168 | + mutation.isPending = isPending; |
| 169 | + mutation.error = errorSignal; |
| 170 | + |
| 171 | + return mutation; |
| 172 | +} |
0 commit comments