|
| 1 | +import { inject, Type } from '@angular/core'; |
| 2 | +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; |
| 3 | +import { Observable, tap } from 'rxjs'; |
| 4 | + |
| 5 | +import { pickType } from '../utilities/reactive-x'; |
| 6 | +import { CommandBus, CommandEventBus } from './buses'; |
| 7 | +import { Command, CommandEvent } from './core'; |
| 8 | +import { CommandFlowScheduler } from './scheduler'; |
| 9 | + |
| 10 | +export interface CommandHandler<C extends Command> { |
| 11 | + (stream: Observable<C>): Observable<void | CommandEvent<C>>; |
| 12 | +} |
| 13 | + |
| 14 | +export interface CommandEventHandler<E extends CommandEvent> { |
| 15 | + (stream: Observable<E>): Observable<void | Command>; |
| 16 | +} |
| 17 | + |
| 18 | +export function registerCommandHandler<Types extends Type<Command>[]>( |
| 19 | + types: Types, |
| 20 | + handler: CommandHandler<InstanceType<Types[number]>>, |
| 21 | +): void { |
| 22 | + const commands$ = inject(CommandBus); |
| 23 | + const events$ = inject(CommandEventBus); |
| 24 | + const scheduler = inject(CommandFlowScheduler); |
| 25 | + commands$ |
| 26 | + .pipe( |
| 27 | + takeUntilDestroyed(), |
| 28 | + pickType(...types), |
| 29 | + handler, |
| 30 | + pickType(CommandEvent), |
| 31 | + tap((event) => scheduler.next(() => events$.publish(event))), |
| 32 | + ) |
| 33 | + .subscribe(); |
| 34 | +} |
| 35 | + |
| 36 | +export function registerCommandEventHandler<Types extends Type<CommandEvent>[]>( |
| 37 | + types: Types, |
| 38 | + handler: CommandEventHandler<InstanceType<Types[number]>>, |
| 39 | +): void { |
| 40 | + const events$ = inject(CommandEventBus); |
| 41 | + const commands$ = inject(CommandBus); |
| 42 | + const scheduler = inject(CommandFlowScheduler); |
| 43 | + events$ |
| 44 | + .pipe( |
| 45 | + takeUntilDestroyed(), |
| 46 | + pickType(...types), |
| 47 | + handler, |
| 48 | + pickType(Command), |
| 49 | + tap((command) => scheduler.next(() => commands$.dispatch(command))), |
| 50 | + ) |
| 51 | + .subscribe(); |
| 52 | +} |
0 commit comments