-
Notifications
You must be signed in to change notification settings - Fork 324
/
httpclient.ts
52 lines (46 loc) · 1.47 KB
/
httpclient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import {
isJsonRpcErrorResponse,
JsonRpcRequest,
JsonRpcSuccessResponse,
parseJsonRpcResponse,
} from "@cosmjs/json-rpc";
import { http } from "./http";
import { hasProtocol, RpcClient } from "./rpcclient";
export interface HttpEndpoint {
/**
* The URL of the HTTP endpoint.
*
* For POST APIs like Tendermint RPC in CosmJS,
* this is without the method specific paths (e.g. https://cosmoshub-4--rpc--full.datahub.figment.io/)
*/
readonly url: string;
/**
* HTTP headers that are sent with every request, such as authorization information.
*/
readonly headers: Record<string, string>;
}
export class HttpClient implements RpcClient {
protected readonly url: string;
protected readonly headers: Record<string, string> | undefined;
public constructor(endpoint: string | HttpEndpoint) {
if (typeof endpoint === "string") {
if (!hasProtocol(endpoint)) {
throw new Error("Endpoint URL is missing a protocol. Expected 'https://' or 'http://'.");
}
this.url = endpoint;
} else {
this.url = endpoint.url;
this.headers = endpoint.headers;
}
}
public disconnect(): void {
// nothing to be done
}
public async execute(request: JsonRpcRequest): Promise<JsonRpcSuccessResponse> {
const response = parseJsonRpcResponse(await http("POST", this.url, this.headers, request));
if (isJsonRpcErrorResponse(response)) {
throw new Error(JSON.stringify(response.error));
}
return response;
}
}