Skip to content

Commit

Permalink
fix(batching): add error tests
Browse files Browse the repository at this point in the history
  • Loading branch information
shanejonas committed Jul 25, 2019
1 parent c867faa commit 46e8eec
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 9 deletions.
57 changes: 54 additions & 3 deletions src/RequestManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,28 @@ describe("client-js", () => {
c.request("foo", []);
});

it("can batch a request", async () => {
it("can error on batchng a request", async () => {
const transport = new EventEmitterTransport("foo://unique-uri");
const c = new RequestManager([transport]);
return c.connect().then(() => {
expect(() => c.endBatch()).toThrow();
});
});

it("can return errors on batchng requests", async () => {
const transport = new EventEmitterTransport("foo://unique-uri");
transport.sendData = (data) => {
const result = JSON.stringify([
{
jsonrpc: "2.0",
id: 3,
result: "foo",
error: {
code: 509,
message: "too much 509",
data: {
test: "data",
},
},
},
{
jsonrpc: "2.0",
Expand All @@ -57,6 +71,43 @@ describe("client-js", () => {
transport.connection.emit("message", result);
};

const c = new RequestManager([transport]);
return c.connect().then(() => {
c.startBatch();
const requests = [
c.request("foo", []),
c.request("foo", []),
];
c.endBatch();
expect(Promise.all(requests)).rejects.toEqual({
code: 509,
message: "too much 509",
data: {
test: "data",
},
});
c.close();
});
});

it("can batch a request", async () => {
const transport = new EventEmitterTransport("foo://unique-uri");
transport.sendData = (data) => {
const result = JSON.stringify([
{
jsonrpc: "2.0",
id: 5,
result: "foo",
},
{
jsonrpc: "2.0",
id: 6,
result: "bar",
},
]);
transport.connection.emit("message", result);
};

const c = new RequestManager([transport]);
return c.connect().then(() => {
c.startBatch();
Expand All @@ -81,7 +132,7 @@ describe("client-js", () => {
transport.connection.on("message", () => {
fn(JSON.stringify({
jsonrpc: "2.0",
id: 3,
id: 7,
error: {
code: 0,
message: "out of order",
Expand Down
14 changes: 8 additions & 6 deletions src/RequestManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,14 +114,16 @@ class RequestManager {

private onData(data: string): void {
const parsedData: IJSONRPCResponse[] | IJSONRPCResponse = JSON.parse(data);
// handle batch requests
if (Array.isArray(parsedData)) {
parsedData.forEach((response) => {
if (this.requests[response.id]) {
if (response.error) {
this.requests[response.id].reject(new Error(response.error.message));
} else {
this.requests[response.id].resolve(response.result);
}
if (!this.requests[response.id]) {
return;
}
if (response.error) {
this.requests[response.id].reject(response.error);
} else {
this.requests[response.id].resolve(response.result);
}
});
return;
Expand Down

0 comments on commit 46e8eec

Please sign in to comment.