2017-08-07 23:45:08 -04:00
|
|
|
import { randomBytes } from 'crypto';
|
2017-09-24 19:06:28 -07:00
|
|
|
import { JsonRpcResponse, RPCRequest } from './types';
|
2017-08-23 02:57:18 -04:00
|
|
|
|
2017-08-07 23:45:08 -04:00
|
|
|
export default class RPCClient {
|
2017-09-24 19:06:28 -07:00
|
|
|
public endpoint: string;
|
2017-11-30 11:36:10 -06:00
|
|
|
public headers: { [key: string]: string };
|
|
|
|
constructor(endpoint: string, headers: { [key: string]: string } = {}) {
|
2017-08-07 23:45:08 -04:00
|
|
|
this.endpoint = endpoint;
|
2017-11-18 13:33:53 -07:00
|
|
|
this.headers = headers;
|
2017-08-07 23:45:08 -04:00
|
|
|
}
|
|
|
|
|
2017-11-30 00:35:17 -05:00
|
|
|
public id(): string | number {
|
2017-09-19 20:47:08 -04:00
|
|
|
return randomBytes(16).toString('hex');
|
|
|
|
}
|
|
|
|
|
2017-09-24 19:06:28 -07:00
|
|
|
public decorateRequest = (req: RPCRequest) => ({
|
|
|
|
...req,
|
|
|
|
id: this.id(),
|
|
|
|
jsonrpc: '2.0'
|
|
|
|
});
|
2017-09-19 20:47:08 -04:00
|
|
|
|
2017-09-24 19:06:28 -07:00
|
|
|
public call = (request: RPCRequest | any): Promise<JsonRpcResponse> => {
|
2017-08-07 23:45:08 -04:00
|
|
|
return fetch(this.endpoint, {
|
|
|
|
method: 'POST',
|
2017-11-30 00:35:17 -05:00
|
|
|
headers: this.createHeaders({
|
2017-11-18 13:33:53 -07:00
|
|
|
'Content-Type': 'application/json',
|
2017-11-29 15:14:57 -08:00
|
|
|
...this.headers
|
2017-11-30 00:35:17 -05:00
|
|
|
}),
|
2017-09-19 20:47:08 -04:00
|
|
|
body: JSON.stringify(this.decorateRequest(request))
|
2017-08-07 23:45:08 -04:00
|
|
|
}).then(r => r.json());
|
2017-09-24 19:06:28 -07:00
|
|
|
};
|
2017-08-07 23:45:08 -04:00
|
|
|
|
2017-09-24 19:06:28 -07:00
|
|
|
public batch = (requests: RPCRequest[] | any): Promise<JsonRpcResponse[]> => {
|
2017-08-07 23:45:08 -04:00
|
|
|
return fetch(this.endpoint, {
|
|
|
|
method: 'POST',
|
2017-11-30 00:35:17 -05:00
|
|
|
headers: this.createHeaders({
|
2017-11-18 13:33:53 -07:00
|
|
|
'Content-Type': 'application/json',
|
2017-11-29 15:14:57 -08:00
|
|
|
...this.headers
|
2017-11-30 00:35:17 -05:00
|
|
|
}),
|
2017-09-19 20:47:08 -04:00
|
|
|
body: JSON.stringify(requests.map(this.decorateRequest))
|
2017-08-07 23:45:08 -04:00
|
|
|
}).then(r => r.json());
|
2017-09-24 19:06:28 -07:00
|
|
|
};
|
2017-11-30 00:35:17 -05:00
|
|
|
|
2018-03-07 18:36:05 -05:00
|
|
|
private createHeaders = (headerObject: HeadersInit) => {
|
2017-11-30 00:35:17 -05:00
|
|
|
const headers = new Headers();
|
2018-03-07 18:36:05 -05:00
|
|
|
Object.entries(headerObject).forEach(([name, value]) => {
|
|
|
|
headers.append(name, value);
|
2017-11-30 00:35:17 -05:00
|
|
|
});
|
|
|
|
return headers;
|
|
|
|
};
|
2017-08-07 23:45:08 -04:00
|
|
|
}
|