1
0
Fork 0
mirror of https://github.com/immich-app/immich.git synced 2025-01-10 13:56:47 +01:00
immich/web/src/lib/utils/eventemitter.ts
2024-02-16 15:43:40 -05:00

42 lines
1.2 KiB
TypeScript

import type {
DefaultEventsMap,
EventsMap,
ReservedOrUserEventNames,
ReservedOrUserListener,
} from '@socket.io/component-emitter';
import type { Socket } from 'socket.io-client';
export function createEventEmitter<
ListenEvents extends EventsMap = DefaultEventsMap,
EmitEvents extends EventsMap = ListenEvents,
ReservedEvents extends EventsMap = NonNullable<unknown>,
>(socket: Socket<ListenEvents, EmitEvents>) {
function on<Ev extends ReservedOrUserEventNames<ReservedEvents, ListenEvents>>(
ev: Ev,
listener: ReservedOrUserListener<ReservedEvents, ListenEvents, Ev>,
) {
socket.on(ev, listener);
return () => {
socket.off(ev, listener);
};
}
function once<Ev extends ReservedOrUserEventNames<ReservedEvents, ListenEvents>>(
ev: Ev,
listener: ReservedOrUserListener<ReservedEvents, ListenEvents, Ev>,
) {
socket.once(ev, listener);
return () => {
socket.off(ev, listener);
};
}
function off<Ev extends ReservedOrUserEventNames<ReservedEvents, ListenEvents>>(
ev: Ev,
listener: ReservedOrUserListener<ReservedEvents, ListenEvents, Ev>,
) {
socket.off(ev, listener);
}
return { on, once, off };
}