-
Notifications
You must be signed in to change notification settings - Fork 568
/
socketio.ts
80 lines (68 loc) 路 1.75 KB
/
socketio.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import type { ManagerOptions, SocketOptions, Socket } from 'socket.io-client';
export interface MidwaySocketIOClientOptions
extends Partial<ManagerOptions & SocketOptions> {
url?: string;
protocol?: string;
host?: string;
namespace?: string;
port?: any;
}
export class SocketIOWrapperClient {
private readonly socket: Socket;
constructor(socket) {
this.socket = socket;
}
async connect() {
return new Promise((resolve, reject) => {
this.socket.on('connect', () => {
resolve(this.socket);
});
});
}
getSocket() {
return this.socket;
}
send(eventName: string, ...args) {
this.socket.emit(eventName, ...args);
}
on(eventName: string, handler) {
this.socket.on(eventName, handler);
}
once(eventName: string, handler) {
return this.socket.once(eventName, handler);
}
removeListener(event: string, fn?) {
return this.socket.removeListener(event, fn);
}
emit(eventName: string, ...args) {
return this.socket.emit(eventName, ...args);
}
async sendWithAck(eventName: string, ...args) {
return new Promise((resolve, reject) => {
this.socket.emit(eventName, ...args, resolve);
});
}
close() {
this.socket.close();
}
}
export async function createSocketIOClient(
opts: MidwaySocketIOClientOptions
): Promise<SocketIOWrapperClient & NodeJS.EventEmitter> {
let url;
if (opts.url) {
url = opts.url;
} else {
url = `${opts.protocol || 'http'}://${opts.host || '127.0.0.1'}:${
opts.port || 80
}`;
delete opts['port'];
}
if (opts.namespace) {
url += opts.namespace;
}
const socket = require('socket.io-client')(url, opts);
const client = new SocketIOWrapperClient(socket);
await client.connect();
return client as any;
}