SIOClients.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import wildcard from "socketio-wildcard"
  2. import ClientV2 from "socket.io-client-v2"
  3. import { io as ClientV4, Socket as SocketV4 } from "socket.io-client-v4"
  4. import { io as ClientV3, Socket as SocketV3 } from "socket.io-client-v3"
  5. type Options = {
  6. path: string
  7. auth: {
  8. token: string | undefined
  9. }
  10. }
  11. type PossibleEvent =
  12. | "connect"
  13. | "connect_error"
  14. | "reconnect_error"
  15. | "error"
  16. | "disconnect"
  17. | "*"
  18. export interface SIOClient {
  19. connect(url: string, opts?: Options): void
  20. on(event: PossibleEvent, cb: (data: any) => void): void
  21. emit(event: string, data: any, cb: (data: any) => void): void
  22. close(): void
  23. }
  24. export class SIOClientV4 implements SIOClient {
  25. private client: SocketV4 | undefined
  26. connect(url: string, opts?: Options) {
  27. this.client = ClientV4(url, opts)
  28. }
  29. on(event: PossibleEvent, cb: (data: any) => void) {
  30. this.client?.on(event, cb)
  31. }
  32. emit(event: string, data: any, cb: (data: any) => void): void {
  33. this.client?.emit(event, data, cb)
  34. }
  35. close(): void {
  36. this.client?.close()
  37. }
  38. }
  39. export class SIOClientV3 implements SIOClient {
  40. private client: SocketV3 | undefined
  41. connect(url: string, opts?: Options) {
  42. this.client = ClientV3(url, opts)
  43. }
  44. on(event: PossibleEvent, cb: (data: any) => void): void {
  45. this.client?.on(event, cb)
  46. }
  47. emit(event: string, data: any, cb: (data: any) => void): void {
  48. this.client?.emit(event, data, cb)
  49. }
  50. close(): void {
  51. this.client?.close()
  52. }
  53. }
  54. export class SIOClientV2 implements SIOClient {
  55. private client: any | undefined
  56. connect(url: string, opts?: Options) {
  57. this.client = new ClientV2(url, opts)
  58. wildcard(ClientV2.Manager)(this.client)
  59. }
  60. on(event: PossibleEvent, cb: (data: any) => void): void {
  61. this.client?.on(event, cb)
  62. }
  63. emit(event: string, data: any, cb: (data: any) => void): void {
  64. this.client?.emit(event, data, cb)
  65. }
  66. close(): void {
  67. this.client?.close()
  68. }
  69. }