fcs
2025-04-10 0163870d662dc5b7d69ceff977490ede594f7d82
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
 
"use strict";
 
/**
 * @class
 */
module.exports = class Socket {
  /**
   * Socket constructor.
   * Called when a socket gets connected and attaches any listeners and middleware to the event chain.
   * @param socket <Socket.io Socket>}
   * @param listeners <Map> list of events and handlers
   * @param middleware <Function> composed middleware function
   */
  constructor( socket, listeners, middleware ) {
    this.socket = socket
 
    // The composed middleware function
    this.middleware = null
 
    // Append listeners and composed middleware function
    this.update( listeners, middleware )
  }
 
  /**
   * Adds a specific event and callback to this socket
   * @param event <String>
   * @param data <?>
   */
  on( event, handler ) {
    this.socket.on( event, ( data, cb ) => {
      let packet = {
        event: event,
        data: data,
        socket: this, 
        acknowledge: cb
      }
 
      if ( !this.middleware ) {
        handler( packet, data )
        return
      }
 
      this.middleware( packet )
        .then( () => {
          handler( packet, data )
        })
    })
  }
 
  /**
   * Registers the new list of listeners and middleware composition
   * @param listeners <Map> map of events and callbacks
   * @param middleware <Function> the composed middleware
   */
  update( listeners, middleware ) {
    this.socket.removeAllListeners()
    this.middleware = middleware
 
    listeners.forEach( ( handlers, event ) => {
      if ( event === 'connection' ) {
        return
      }
 
      handlers.forEach( handler => {
        this.on( event, handler )
      })
    })
  }
 
  /**
   * Getter for the socket id
   * @type <String>
   */
  get id() {
    return this.socket.id
  }
 
  /**
   * Helper through to the socket
   * @param event <String>
   * @param packet <?>
   */
  emit( event, packet ) {
    this.socket.emit( event, packet )
  }
 
  /**
   * Helper through to broadcasting
   * @param event <String>
   * @param packet <?>
   */
  broadcast( event, packet ) {
    this.socket.broadcast.emit( event, packet )
  }
 
  /**
   * Disconnect helper
   */
  disconnect() {
    this.socket.disconnect()
  }
}