Skip to content

Commit

Permalink
Support for customizable logger for incoming/outgoing messages (#93)
Browse files Browse the repository at this point in the history
* fork

* revert

* update gitignore

* support logger poc

* narrow down to a func

* remove src and dst from api

* assert with jest func
  • Loading branch information
weizman authored Jun 15, 2023
1 parent c3787a3 commit e1c6171
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.DS_Store
.idea/
coverage/
dist/
dist-test/
Expand Down
16 changes: 16 additions & 0 deletions src/BasePostMessageStream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,22 @@ describe('BasePostMessageStream', () => {
stream.destroy();
});

it('checks logger receiving messages', () => {
const log = jest.fn();
stream._setLogger(log);
(stream as any)._init = true;
(stream as any)._onData({ data: 123 });
expect(log).toHaveBeenCalledWith({ data: 123 }, false);
});

it('checks logger sending messages', () => {
const log = jest.fn();
stream._setLogger(log);
(stream as any)._init = true;
(stream as any)._write({ data: 123 }, null, () => undefined);
expect(log).toHaveBeenCalledWith({ data: 123 }, true);
});

it('handles errors thrown when pushing data', async () => {
await new Promise<void>((resolve) => {
stream.push = () => {
Expand Down
13 changes: 13 additions & 0 deletions src/BasePostMessageStream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ const noop = () => undefined;
const SYN = 'SYN';
const ACK = 'ACK';

type Log = (data: unknown, out: boolean) => void;

export interface PostMessageEvent {
data?: StreamData;
origin: string;
Expand All @@ -20,6 +22,8 @@ export abstract class BasePostMessageStream extends Duplex {

private _haveSyn: boolean;

private _log: Log;

constructor() {
super({
objectMode: true,
Expand All @@ -28,6 +32,7 @@ export abstract class BasePostMessageStream extends Duplex {
// Initialization flags
this._init = false;
this._haveSyn = false;
this._log = () => null;
}

/**
Expand All @@ -45,6 +50,7 @@ export abstract class BasePostMessageStream extends Duplex {
// Forward message
try {
this.push(data);
this._log(data, false);
} catch (err) {
this.emit('error', err);
}
Expand All @@ -71,7 +77,14 @@ export abstract class BasePostMessageStream extends Duplex {
}

_write(data: StreamData, _encoding: string | null, cb: () => void): void {
if (data !== ACK && data !== SYN) {
this._log(data, true);
}
this._postMessage(data);
cb();
}

_setLogger(log: Log) {
this._log = log;
}
}

0 comments on commit e1c6171

Please sign in to comment.