11import Pusher from "pusher-js" ;
22import { env } from "@/env" ;
3+ import type {
4+ RealtimeListenHandlers ,
5+ RealtimePusherEvent ,
6+ } from "./realtime-events" ;
7+
8+ export {
9+ REALTIME_PUSHER_EVENTS ,
10+ type RealtimeListenHandlers ,
11+ type RealtimePusherEvent ,
12+ } from "./realtime-events" ;
313
414let _pusherClient : Pusher | null = null ;
515
@@ -23,40 +33,25 @@ function getPusherClient(): Pusher | null {
2333 return _pusherClient ;
2434}
2535
26- type EventHandlers = Record < string , ( ) => void > ;
27-
28- export function listenChannel (
29- channel : string ,
30- handlers : EventHandlers ,
31- ) : ( ) => void ;
3236export function listenChannel (
3337 channel : string ,
34- event : string ,
35- handler : ( ) => void ,
36- ) : ( ) => void ;
37- export function listenChannel (
38- channel : string ,
39- eventOrHandlers : string | EventHandlers ,
40- handler ?: ( ) => void ,
38+ handlers : RealtimeListenHandlers ,
4139) : ( ) => void {
42- const handlers : EventHandlers =
43- typeof eventOrHandlers === "string" && handler !== undefined
44- ? { [ eventOrHandlers ] : handler }
45- : ( eventOrHandlers as EventHandlers ) ;
46-
4740 const pusher = getPusherClient ( ) ;
4841 if ( ! pusher ) {
4942 return ( ) => { } ;
5043 }
5144
5245 const ch = pusher . subscribe ( channel ) ;
53- for ( const [ event , fn ] of Object . entries ( handlers ) ) {
54- ch . bind ( event , fn ) ;
46+ for ( const event of Object . keys ( handlers ) as RealtimePusherEvent [ ] ) {
47+ const fn = handlers [ event ] ;
48+ if ( fn ) ch . bind ( event , fn ) ;
5549 }
5650
5751 return ( ) => {
58- for ( const [ event , fn ] of Object . entries ( handlers ) ) {
59- ch . unbind ( event , fn ) ;
52+ for ( const event of Object . keys ( handlers ) as RealtimePusherEvent [ ] ) {
53+ const fn = handlers [ event ] ;
54+ if ( fn ) ch . unbind ( event , fn ) ;
6055 }
6156 pusher . unsubscribe ( channel ) ;
6257 } ;
0 commit comments