|
| 1 | +import { patchState, signalStoreFeature, withComputed, withState, WritableStateSource } from '@ngrx/signals'; |
| 2 | +import { Observable, Subject, mergeMap, concatMap, switchMap, exhaustMap, OperatorFunction, tap, catchError, of, firstValueFrom } from 'rxjs'; |
| 3 | +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; |
| 4 | +import { inject, Injector, DestroyRef, computed } from '@angular/core'; |
| 5 | + |
| 6 | +// |
| 7 | +// CREDITS: This implementation is highly influenced by Marko Stanimirović' prototype: |
| 8 | +// https://github.com/markostanimirovic/rx-resource-proto |
| 9 | +// |
| 10 | +// Big thanks to Marko for sharing his knowledge and for his great work! |
| 11 | +// |
| 12 | + |
| 13 | +export interface MutationState { |
| 14 | + _mutationCount: number; |
| 15 | + mutationError: string | null; |
| 16 | +} |
| 17 | + |
| 18 | +const incrementCounter = (state: MutationState) => ({ ...state, _mutationCount: state._mutationCount + 1 }); |
| 19 | +const decrementCounter = (state: MutationState) => ({ ...state, _mutationCount: state._mutationCount - 1 }); |
| 20 | + |
| 21 | +export const clearMutationError = (state: MutationState) => ({ ...state, mutationError: null }); |
| 22 | + |
| 23 | +export type FlatteningOperator = 'merge' | 'concat' | 'switch' | 'exhaust'; |
| 24 | + |
| 25 | + |
| 26 | +export interface MutationOptions<P, R> { |
| 27 | + operation: (params: P) => Observable<R>; |
| 28 | + onSuccess?: (params: P, result: R) => void; |
| 29 | + onError?: (params: P, error: unknown) => string | void; |
| 30 | + operator?: FlatteningOperator; |
| 31 | + injector?: Injector; |
| 32 | +} |
| 33 | + |
| 34 | +function flatten<P, R>(operation: (params: P) => Observable<R>, operator: FlatteningOperator): OperatorFunction<P, R> { |
| 35 | + switch (operator) { |
| 36 | + case 'concat': |
| 37 | + return concatMap(operation); |
| 38 | + case 'switch': |
| 39 | + return switchMap(operation); |
| 40 | + case 'exhaust': |
| 41 | + return exhaustMap(operation); |
| 42 | + case 'merge': |
| 43 | + default: |
| 44 | + return mergeMap(operation); |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +export function rxMutation<P, R>( |
| 49 | + store: WritableStateSource<MutationState>, |
| 50 | + options: MutationOptions<P, R> |
| 51 | +) { |
| 52 | + const destroyRef = options.injector?.get(DestroyRef) || inject(DestroyRef); |
| 53 | + const mutationSubject = new Subject<P>(); |
| 54 | + |
| 55 | + const successSubject = new Subject<{params: P, result: R}>(); |
| 56 | + const errorSubject = new Subject<{params: P, error: unknown}>(); |
| 57 | + |
| 58 | + const operator = options.operator || 'merge'; |
| 59 | + const flatteningOp = flatten((params: P) => { |
| 60 | + return options.operation(params).pipe( |
| 61 | + tap((result) => { |
| 62 | + options.onSuccess?.(params, result); |
| 63 | + patchState(store, decrementCounter); |
| 64 | + successSubject.next({params, result}); |
| 65 | + }), |
| 66 | + catchError((error) => { |
| 67 | + console.error('Mutation error:', error); |
| 68 | + const mutationError = options.onError?.(params, error) ?? error.message ?? 'Mutation failed'; |
| 69 | + patchState(store, mutationError, decrementCounter); |
| 70 | + errorSubject.next({params, error}); |
| 71 | + return of(null); |
| 72 | + }) |
| 73 | + ); |
| 74 | + }, operator); |
| 75 | + |
| 76 | + mutationSubject.pipe( |
| 77 | + flatteningOp, |
| 78 | + takeUntilDestroyed(destroyRef), |
| 79 | + ).subscribe(); |
| 80 | + |
| 81 | + const result = (params: P) => { |
| 82 | + patchState(store, incrementCounter); |
| 83 | + mutationSubject.next(params); |
| 84 | + }; |
| 85 | + |
| 86 | + result.success = successSubject.asObservable(); |
| 87 | + result.error = errorSubject.asObservable(); |
| 88 | + |
| 89 | + return result; |
| 90 | +} |
| 91 | + |
| 92 | +export function mutation<P, R>( |
| 93 | + store: WritableStateSource<MutationState>, |
| 94 | + options: MutationOptions<P, R> |
| 95 | +): (params: P) => Promise<R> { |
| 96 | + return async (params: P): Promise<R> => { |
| 97 | + patchState(store, incrementCounter); |
| 98 | + try { |
| 99 | + const result = await firstValueFrom(options.operation(params)); |
| 100 | + options.onSuccess?.(params, result); |
| 101 | + return result; |
| 102 | + } catch (error) { |
| 103 | + console.error('Mutation error:', error); |
| 104 | + const mutationError = options.onError?.(params, error) ?? (error instanceof Error ? error.message : 'Mutation failed'); |
| 105 | + patchState(store, { mutationError }); |
| 106 | + throw error; |
| 107 | + } finally { |
| 108 | + patchState(store, decrementCounter); |
| 109 | + } |
| 110 | + }; |
| 111 | +} |
| 112 | + |
| 113 | +export function withMutations() { |
| 114 | + return signalStoreFeature( |
| 115 | + withState<MutationState>({ |
| 116 | + _mutationCount: 0, |
| 117 | + mutationError: null, |
| 118 | + }), |
| 119 | + withComputed((state) => ({ |
| 120 | + isProcessing: computed(() => state._mutationCount() > 0), |
| 121 | + })) |
| 122 | + ); |
| 123 | +} |
0 commit comments