HenryNguyen5 c340246ca0 Enable no-implicit-any (#1263)
* Progress commit

* Update more types

* Fix more types

* Fix abi function types

* Fix lib types

* Fix rest of types

* Address wbobeirne changes

* Change origin and destination check
2018-03-07 17:36:05 -06:00

52 lines
1.4 KiB
TypeScript

import { randomBytes } from 'crypto';
import { JsonRpcResponse, RPCRequest } from './types';
export default class RPCClient {
public endpoint: string;
public headers: { [key: string]: string };
constructor(endpoint: string, headers: { [key: string]: string } = {}) {
this.endpoint = endpoint;
this.headers = headers;
}
public id(): string | number {
return randomBytes(16).toString('hex');
}
public decorateRequest = (req: RPCRequest) => ({
...req,
id: this.id(),
jsonrpc: '2.0'
});
public call = (request: RPCRequest | any): Promise<JsonRpcResponse> => {
return fetch(this.endpoint, {
method: 'POST',
headers: this.createHeaders({
'Content-Type': 'application/json',
...this.headers
}),
body: JSON.stringify(this.decorateRequest(request))
}).then(r => r.json());
};
public batch = (requests: RPCRequest[] | any): Promise<JsonRpcResponse[]> => {
return fetch(this.endpoint, {
method: 'POST',
headers: this.createHeaders({
'Content-Type': 'application/json',
...this.headers
}),
body: JSON.stringify(requests.map(this.decorateRequest))
}).then(r => r.json());
};
private createHeaders = (headerObject: HeadersInit) => {
const headers = new Headers();
Object.entries(headerObject).forEach(([name, value]) => {
headers.append(name, value);
});
return headers;
};
}