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