Skip to content

Commit

Permalink
test: Added test for piped streams
Browse files Browse the repository at this point in the history
  • Loading branch information
leonardoraele committed Dec 30, 2024
1 parent 56a921a commit 28042a8
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
8 changes: 4 additions & 4 deletions src/json-rpc/json-rpc-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,9 @@ export class JsonRpcClient<API extends MethodInterface = Record<string, any>> {
}
}

toStreamPair(): { input: WritableStream<string>, output: ReadableStream<string> } {
const input = new WritableStream<string>({ write: message => this.accept(message) });
const output = new ReadableStream<string>({ start: controller => this.onrequest = message => controller.enqueue(message) });
return { input, output };
toStream(): ReadableWritablePair<string, string> {
const readable = new ReadableStream<string>({ start: controller => this.onrequest = message => controller.enqueue(message) });
const writable = new WritableStream<string>({ write: message => this.accept(message) });
return { readable, writable };
}
}
2 changes: 1 addition & 1 deletion src/json-rpc/json-rpc-dual-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class JsonRpcDualEngine<RemoteAPI extends MethodInterface = any> {
}
}

toStream(): TransformStream<string, string> {
toStream(): ReadableWritablePair<string, string> {
return new TransformStream({
start: controller => this.onmessage = response => controller.enqueue(response),
transform: message => this.accept(message),
Expand Down
27 changes: 26 additions & 1 deletion src/json-rpc/json-rpc-server.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { expect} from 'expect';
import { expect } from 'expect';
import { beforeEach, describe, it, mock } from 'node:test';
import { JsonRpcServer } from './json-rpc-server.js';

Expand Down Expand Up @@ -94,4 +94,29 @@ describe(JsonRpcServer.name, () => {

expect(parsed).toEqual({ jsonrpc: '2.0', result: 'pong', id: 1 });
});

it('should work as a piped stream', async () => {
const input = new ReadableStream({
start(controller) {
controller.enqueue(JSON.stringify({ jsonrpc: '2.0', method: 'ping', id: 1 }));
controller.close();
},
});
const stream = server.toStream();
const output = new WritableStream<string>({
start() {
this.chunks = [];
},
write(chunk) {
this.chunks.push(chunk);
},
close() {
expect(this.chunks).toEqual([JSON.stringify({ jsonrpc: '2.0', result: 'pong', id: 1 })])
},
});

expect.assertions(1);

await input.pipeThrough(stream).pipeTo(output);
});
});

0 comments on commit 28042a8

Please sign in to comment.