channel.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. "use strict";
  2. // TODO: Use native "events" module if in Node.js environment?
  3. const EventEmitter = require('events');
  4. /* A WebSocketChannel exposes an EventEmitter-like API for sending and handling
  5. events or requests over the channel through the attached WebSocketWrapper.
  6. `var channel = new WebSocketChannel(name, socketWrapper);`
  7. - `name` - the namespace for the channel
  8. - `socketWrapper` - the WebSocketWrapper instance to which data should
  9. be sent
  10. */
  11. class WebSocketChannel {
  12. constructor(name, socketWrapper) {
  13. // Channel name; `null` only for the WebSocketWrapper instance
  14. this._name = name;
  15. // Reference to WebSocketWrapper instance
  16. this._wrapper = socketWrapper;
  17. // This channel's EventEmitter
  18. this._emitter = new EventEmitter();
  19. // WeakMap of wrapped event listeners
  20. this._wrappedListeners = new WeakMap();
  21. }
  22. // Retrieve channel name
  23. get name() {
  24. return this._name;
  25. }
  26. // Changing the channel name after it's been created is a bad idea.
  27. set name(name) {
  28. throw new Error("Setting the channel name is not allowed");
  29. }
  30. /* Expose EventEmitter-like API
  31. When `eventName` is one of the `NO_WRAP_EVENTS`, the event handlers
  32. are left untouched, and the emitted events are just sent to the
  33. EventEmitter; otherwise, event listeners are wrapped to process the
  34. incoming request and the emitted events are sent to the WebSocketWrapper
  35. to be serialized and sent over the WebSocket. */
  36. on(eventName, listener) {
  37. if(this._name == null && WebSocketChannel.NO_WRAP_EVENTS.indexOf(eventName) >= 0)
  38. /* Note: The following is equivalent to:
  39. `this._emitter.on(eventName, listener.bind(this));`
  40. But thanks to eventemitter3, the following is a touch faster. */
  41. this._emitter.on(eventName, listener, this);
  42. else
  43. this._emitter.on(eventName, this._wrapListener(listener) );
  44. return this;
  45. }
  46. once(eventName, listener) {
  47. if(this._name == null && WebSocketChannel.NO_WRAP_EVENTS.indexOf(eventName) >= 0)
  48. this._emitter.once(eventName, listener, this);
  49. else
  50. this._emitter.once(eventName, this._wrapListener(listener) );
  51. return this;
  52. }
  53. removeListener(eventName, listener) {
  54. if(this._name == null && WebSocketChannel.NO_WRAP_EVENTS.indexOf(eventName) >= 0)
  55. this._emitter.removeListener(eventName, listener);
  56. else
  57. this._emitter.removeListener(eventName,
  58. this._wrappedListeners.get(listener) );
  59. return this;
  60. }
  61. removeAllListeners(eventName) {
  62. this._emitter.removeAllListeners(eventName);
  63. return this;
  64. }
  65. eventNames() {
  66. return this._emitter.eventNames();
  67. }
  68. listeners(eventName) {
  69. if(this._name == null && WebSocketChannel.NO_WRAP_EVENTS.indexOf(eventName) >= 0)
  70. return this._emitter.listeners(eventName);
  71. else {
  72. return this._emitter.listeners(eventName).map((wrapper) => {
  73. return wrapper._original;
  74. });
  75. }
  76. }
  77. /* The following `emit` and `request` methods will serialize and send the
  78. event over the WebSocket using the WebSocketWrapper. */
  79. emit(eventName) {
  80. if(this._name == null && WebSocketChannel.NO_WRAP_EVENTS.indexOf(eventName) >= 0)
  81. return this._emitter.emit.apply(this._emitter, arguments);
  82. else
  83. return this._wrapper._sendEvent(this._name, eventName, arguments);
  84. }
  85. /* Temporarily set the request timeout for the next request. */
  86. timeout(tempTimeout) {
  87. this._tempTimeout = tempTimeout;
  88. return this;
  89. }
  90. request(eventName) {
  91. var oldTimeout = this._wrapper._requestTimeout;
  92. if(this._tempTimeout !== undefined) {
  93. this._wrapper._requestTimeout = this._tempTimeout;
  94. delete this._tempTimeout;
  95. }
  96. var ret = this._wrapper._sendEvent(this._name, eventName, arguments, true);
  97. this._wrapper._requestTimeout = oldTimeout;
  98. return ret;
  99. }
  100. _wrapListener(listener) {
  101. if(typeof listener !== "function") {
  102. throw new TypeError("\"listener\" argument must be a function");
  103. }
  104. var wrapped = this._wrappedListeners.get(listener);
  105. if(!wrapped) {
  106. wrapped = function channelListenerWrapper(event)
  107. {
  108. /* This function is called when an event is emitted on this
  109. WebSocketChannel's `_emitter` when the WebSocketWrapper
  110. receives an incoming message for this channel. If this
  111. event is a request, special processing is needed to
  112. send the response back over the socket. Below we use
  113. the return value from the original `listener` to
  114. determine what response should be sent back.
  115. `this` refers to the WebSocketChannel instance
  116. `event` has the following properties:
  117. - `name`
  118. - `args`
  119. - `requestId`
  120. */
  121. try {
  122. var returnVal = listener.apply(this, event.args);
  123. } catch(err) {
  124. if(event.requestId >= 0) {
  125. /* If event listener throws, pass that Error back
  126. as a response to the request */
  127. this._wrapper._sendReject(
  128. event.requestId, err);
  129. }
  130. // Re-throw
  131. throw err;
  132. }
  133. if(returnVal instanceof Promise) {
  134. /* If event listener returns a Promise, respond once
  135. the Promise resolves */
  136. returnVal
  137. .then((data) => {
  138. if(event.requestId >= 0) {
  139. this._wrapper._sendResolve(
  140. event.requestId, data);
  141. }
  142. })
  143. .catch((err) => {
  144. if(event.requestId >= 0) {
  145. this._wrapper._sendReject(
  146. event.requestId, err);
  147. }
  148. // else silently ignore error
  149. });
  150. } else if(event.requestId >= 0) {
  151. /* Otherwise, assume that the `returnVal` is what
  152. should be passed back as the response */
  153. this._wrapper._sendResolve(
  154. event.requestId, returnVal);
  155. }
  156. // else return value is ignored for simple events
  157. }.bind(this); // Bind the channel to the `channelListenerWrapper`
  158. // Add a reference back to the original listener
  159. wrapped._original = listener;
  160. this._wrappedListeners.set(listener, wrapped);
  161. }
  162. // Finally, return the wrapped listener
  163. return wrapped;
  164. }
  165. get(key) {
  166. return this._wrapper.get(key);
  167. }
  168. set(key, value) {
  169. this._wrapper.set(key, value);
  170. return this;
  171. }
  172. }
  173. // Add aliases to existing methods
  174. WebSocketChannel.prototype.addListener = WebSocketChannel.prototype.on;
  175. WebSocketChannel.prototype.off = WebSocketChannel.prototype.removeListener;
  176. // List of "special" reserved events whose listeners don't need to be wrapped
  177. WebSocketChannel.NO_WRAP_EVENTS = ["open", "message", "error", "close", "disconnect"];
  178. // Expose the class
  179. module.exports = WebSocketChannel;