diff --git a/src/Client.js b/src/Client.js index 5da8206..c37e3a6 100644 --- a/src/Client.js +++ b/src/Client.js @@ -2,9 +2,9 @@ import WebSocket from 'ws'; import EventEmitter from 'events'; import delay from 'delay'; -import { isFunction } from './utils'; +import { isFunction, noop } from './utils'; -export default class Client { +export default class Client extends EventEmitter { static create(address, options = {}) { return new Promise((resolve, reject) => { const ws = new WebSocket(address); @@ -45,6 +45,8 @@ export default class Client { } constructor(ws, options = {}) { + super(); + const { onClose, onOpen, @@ -99,6 +101,21 @@ export default class Client { if (isFunction(onOpen)) { ws.on('open', onOpen); } if (isFunction(onError)) { ws.on('error', onError); } + + const forward = (eventType) => { + ws.on(eventType, this.emit.bind(this, eventType)); + }; + + this.on('error', noop); + + forward('open'); + forward('close'); + forward('headers'); + forward('error'); + forward('message'); + forward('ping'); + forward('pong'); + forward('unexpected-response'); } onReply(name, listener) { diff --git a/src/Server.js b/src/Server.js index a3bffc8..ca2a3f8 100644 --- a/src/Server.js +++ b/src/Server.js @@ -1,9 +1,11 @@ import WebSocket from 'ws'; +import EventEmitter from 'events'; import pify from 'pify'; import Client from './Client'; +import { noop } from './utils'; -export default class Server { +export default class Server extends EventEmitter { static async create(options) { return new Promise((resolve, reject) => { const connection = new Server(options, (err) => { @@ -14,6 +16,8 @@ export default class Server { } constructor(options, callback) { + super(); + const wss = new WebSocket.Server({ ...options, clientTracking: true, @@ -58,6 +62,16 @@ export default class Server { wss.on('listening', callback); wss.on('error', callback); + + const forward = (eventType) => { + wss.on(eventType, this.emit.bind(this, eventType)); + }; + + this.on('error', noop); + + forward('connection'); + forward('error'); + forward('headers'); } onReply(name, listener) { diff --git a/src/utils.js b/src/utils.js index 8a6eef4..022a924 100644 --- a/src/utils.js +++ b/src/utils.js @@ -2,3 +2,5 @@ export function isFunction(target) { return typeof target === 'function'; } + +export function noop() {}