2017-08-08 03:45:08 +00:00
|
|
|
// @flow
|
|
|
|
import { randomBytes } from 'crypto';
|
2017-09-20 00:47:08 +00:00
|
|
|
import type { RPCRequest, JsonRpcResponse } from './types';
|
2017-08-23 06:57:18 +00:00
|
|
|
|
2017-08-08 03:45:08 +00:00
|
|
|
export default class RPCClient {
|
|
|
|
endpoint: string;
|
|
|
|
constructor(endpoint: string) {
|
|
|
|
this.endpoint = endpoint;
|
|
|
|
}
|
|
|
|
|
2017-09-20 00:47:08 +00:00
|
|
|
id(): string {
|
|
|
|
return randomBytes(16).toString('hex');
|
|
|
|
}
|
|
|
|
|
|
|
|
decorateRequest(req: RPCRequest) {
|
|
|
|
return {
|
|
|
|
...req,
|
|
|
|
id: this.id(),
|
|
|
|
jsonrpc: '2.0'
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2017-08-08 03:45:08 +00:00
|
|
|
async call(request: RPCRequest): Promise<JsonRpcResponse> {
|
|
|
|
return fetch(this.endpoint, {
|
|
|
|
method: 'POST',
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json'
|
|
|
|
},
|
2017-09-20 00:47:08 +00:00
|
|
|
body: JSON.stringify(this.decorateRequest(request))
|
2017-08-08 03:45:08 +00:00
|
|
|
}).then(r => r.json());
|
|
|
|
}
|
|
|
|
|
|
|
|
async batch(requests: RPCRequest[]): Promise<JsonRpcResponse[]> {
|
|
|
|
return fetch(this.endpoint, {
|
|
|
|
method: 'POST',
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json'
|
|
|
|
},
|
2017-09-20 00:47:08 +00:00
|
|
|
body: JSON.stringify(requests.map(this.decorateRequest))
|
2017-08-08 03:45:08 +00:00
|
|
|
}).then(r => r.json());
|
|
|
|
}
|
|
|
|
}
|