Skip to content

Commit

Permalink
extends EventEmitter
Browse files Browse the repository at this point in the history
  • Loading branch information
Cap32 committed Nov 27, 2017
1 parent d745482 commit 176a60a
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
21 changes: 19 additions & 2 deletions src/Client.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -45,6 +45,8 @@ export default class Client {
}

constructor(ws, options = {}) {
super();

const {
onClose,
onOpen,
Expand Down Expand Up @@ -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) {
Expand Down
16 changes: 15 additions & 1 deletion src/Server.js
Original file line number Diff line number Diff line change
@@ -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) => {
Expand All @@ -14,6 +16,8 @@ export default class Server {
}

constructor(options, callback) {
super();

const wss = new WebSocket.Server({
...options,
clientTracking: true,
Expand Down Expand Up @@ -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) {
Expand Down
2 changes: 2 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@
export function isFunction(target) {
return typeof target === 'function';
}

export function noop() {}

0 comments on commit 176a60a

Please sign in to comment.