dispatcher.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict'
  2. const EventEmitter = require('node:events')
  3. class Dispatcher extends EventEmitter {
  4. dispatch () {
  5. throw new Error('not implemented')
  6. }
  7. close () {
  8. throw new Error('not implemented')
  9. }
  10. destroy () {
  11. throw new Error('not implemented')
  12. }
  13. compose (...args) {
  14. // So we handle [interceptor1, interceptor2] or interceptor1, interceptor2, ...
  15. const interceptors = Array.isArray(args[0]) ? args[0] : args
  16. let dispatch = this.dispatch.bind(this)
  17. for (const interceptor of interceptors) {
  18. if (interceptor == null) {
  19. continue
  20. }
  21. if (typeof interceptor !== 'function') {
  22. throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`)
  23. }
  24. dispatch = interceptor(dispatch)
  25. if (dispatch == null || typeof dispatch !== 'function' || dispatch.length !== 2) {
  26. throw new TypeError('invalid interceptor')
  27. }
  28. }
  29. return new ComposedDispatcher(this, dispatch)
  30. }
  31. }
  32. class ComposedDispatcher extends Dispatcher {
  33. #dispatcher = null
  34. #dispatch = null
  35. constructor (dispatcher, dispatch) {
  36. super()
  37. this.#dispatcher = dispatcher
  38. this.#dispatch = dispatch
  39. }
  40. dispatch (...args) {
  41. this.#dispatch(...args)
  42. }
  43. close (...args) {
  44. return this.#dispatcher.close(...args)
  45. }
  46. destroy (...args) {
  47. return this.#dispatcher.destroy(...args)
  48. }
  49. }
  50. module.exports = Dispatcher