mock-socket icon indicating copy to clipboard operation
mock-socket copied to clipboard

Recording/Replay support

Open rijnhard opened this issue 6 years ago • 3 comments

Before I go figuring out how to do this myself, is there any known way of recording and replaying responses? Like polly.js.

I'm thinking of trying to give it a bash of writing a polly.js adapter and using this for the replay side of things

rijnhard avatar Jun 02 '19 11:06 rijnhard

http://reactivex.io/ is your friend.

sechel avatar Jul 24 '19 09:07 sechel

@sechel thanks for the unhelpful opinion. Not to be ungrateful, but jumping into something like reactivex is no simple task, nor do I think should be undertaken half-heartedly.

An example would have gone a log way to prove the contrary.

rijnhard avatar Jul 26 '19 09:07 rijnhard

Hey @rijnhard, here is an example:

import { Server, WebSocket as MockSocket } from 'mock-socket';
import { ReplaySubject } from 'rxjs/ReplaySubject';

export class MockServer extends Server {

  public queue = new ReplaySubject<string>();

  public constructor(url: string) {
    super(url);
    this.on('connection', this.onConnect.bind(this));
  }

  private onConnect(socket: MockSocket) {
    const subscription = this.queue.subscribe(this.emit.bind(this, 'message'));
    socket.on('message', (message: string) => this.publish(message));
    socket.onclose = () => subscription.unsubscribe();
  }

  public publish(message: string) {
    this.queue.next(message);
  }

}

When a new socket connects it subscribes to the ReplaySubject which in turn dispatches all messages that have been queued so far to the socket. On close we unsubscribe from the subject. A new message can be published by either calling publish or by sending a message via any of the socket connections.

sechel avatar Jul 26 '19 11:07 sechel