Skip to content

Commit

Permalink
fix ID jsonrpc rules to conform to spec
Browse files Browse the repository at this point in the history
  • Loading branch information
silesky committed Jan 2, 2022
1 parent 1d97147 commit ee16cb7
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
21 changes: 14 additions & 7 deletions src/utils/jsonrpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,12 @@ import { Either, ErrorResponse, SuccessResponse } from "./either";
import { hasProperties, isObject } from "./exists";

export interface JsonRpcError {
jsonrpc: "2.0";
code: number;
message: string;
data?: any;
id: null | string | number;
}

export const isJsonRpcError = (v: object): v is JsonRpcError => {
return hasProperties(v, "code", "message");
};

interface IJsonRpcResponse {
jsonrpc: "2.0";
id?: string;
Expand Down Expand Up @@ -54,13 +51,23 @@ export function assertJsonRpcReply<T>(
}
if (!hasProperties(v, "jsonrpc")) {
throw new InvalidJsonRpcResponseError(
`Invalid response ${JSON.stringify(v, undefined, 2)}`
`Response should contain "jsonrpc: "2.0""`
);
}
if (!hasProperties(v, "id")) {
throw new InvalidJsonRpcResponseError(
`Response must have an ID property (even if that ID is null)`
);
}
if (v.id === undefined) {
throw new InvalidJsonRpcResponseError(
"Response ID should be null rather than undefined"
);
}
if (hasProperties(v, "result", "error")) {
if (v.result && v.error) {
throw new InvalidJsonRpcResponseError(
"Result and error member should not exist together (https://www.jsonrpc.org/specification#5)"
"Result and error member should not exist together"
);
}
}
Expand Down
2 changes: 2 additions & 0 deletions test/fixtures/batch-with-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ export const response = [
code: -32601,
message: "Method not found",
},
id: null,
},
{
jsonrpc: "2.0",
result: {
name: "john",
},
id: 123,
},
];
1 change: 1 addition & 0 deletions test/fixtures/with-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ export const response = {
code: -32601,
message: "Method not found",
},
id: null,
};

0 comments on commit ee16cb7

Please sign in to comment.