Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / pass / store / sagas / events / channel.factory.ts
blob8593f06ca203832901c449e7e939d08a3ab5c589
1 import { eventChannel } from 'redux-saga';
3 import { type EventManagerEvent, eventManager } from '@proton/pass/lib/events/manager';
4 import { merge } from '@proton/pass/utils/object/merge';
6 import type { EventChannel, EventChannelOnError, EventChannelOptions } from './types';
8 const channelErrorHandler = <T extends {}>(onError?: EventChannelOnError<T>) => {
9     const wrappedOnError: EventChannelOnError<T> = function* (error, eventsChannel, options) {
10         yield onError?.(error, eventsChannel, options);
12         if (error instanceof Error && ['LockedSession', 'InactiveSession'].includes(error.name)) {
13             eventsChannel.channel.close();
14         }
15     };
17     return wrappedOnError;
20 export const eventChannelFactory = <T extends {}>(config: EventChannelOptions<T>) => {
21     const { onClose, onError } = config;
22     const manager = eventManager<T>(config);
24     return merge(config, {
25         onError: channelErrorHandler<T>(onError),
26         manager,
27         channel: eventChannel<EventManagerEvent<T>>((emitter) => {
28             const unsubscribe = manager.subscribe(emitter);
30             return () => {
31                 onClose?.();
32                 unsubscribe();
33                 manager.stop();
34                 manager.reset();
35             };
36         }),
37     }) as EventChannel<T>;