MCPcopy
hub / github.com/msgbyte/tianji / useSocket

Function useSocket

src/client/api/socketio.ts:63–110  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

61>[1];
62
63export function useSocket() {
64 const socket = useSocketStore((state) => state.socket);
65
66 const emit = useEvent(
67 async <T extends keyof SocketEventMap>(
68 eventName: T,
69 eventData: SocketEventData<T>
70 ): Promise<SocketEventRet<T>> => {
71 if (!socket) {
72 throw new Error('Socketio not init');
73 }
74
75 return await socket.emitWithAck(eventName, eventData);
76 }
77 );
78
79 const subscribe = useEvent(
80 <T extends keyof SubscribeEventMap>(
81 name: T,
82 onData: (data: SubscribeEventData<T>) => void
83 ) => {
84 if (!socket) {
85 throw new Error('Socketio not init');
86 }
87
88 const p = emit('$subscribe', { name });
89
90 const receiveDataUpdate = (data: any) => {
91 onData(data);
92 };
93
94 const unsubscribe = () => {
95 Promise.resolve(p).then((cursor) => {
96 emit('$unsubscribe', { name, cursor });
97 socket.off(`${name}#${cursor}` as string, receiveDataUpdate);
98 });
99 };
100
101 Promise.resolve(p).then((cursor) => {
102 socket.on(`${name}#${cursor}` as string, receiveDataUpdate);
103 });
104
105 return unsubscribe;
106 }
107 );
108
109 return { socket, emit, subscribe };
110}
111
112export function useSocketSubscribe<K extends keyof SubscribeEventMap>(
113 name: K,

Callers 4

useServerMapFunction · 0.90
useSocketSubscribeFunction · 0.85
useSocketSubscribeDataFunction · 0.85
useSocketSubscribeListFunction · 0.85

Calls 2

useEventFunction · 0.90
thenMethod · 0.80

Tested by

no test coverage detected