1 |
|
2 |
|
3 |
|
4 |
|
5 | import { Logger } from '@polkadot/util/types';
|
6 | import { RpcCoder } from '../coder/json/types';
|
7 | import { ProviderInterface, ProviderInterface$Callback, ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
8 |
|
9 | import './polyfill';
|
10 |
|
11 | import assert from '@polkadot/util/assert';
|
12 | import logger from '@polkadot/util/logger';
|
13 |
|
14 | import coder from '../coder/json';
|
15 |
|
16 | const ERROR_SUBSCRIBE = 'HTTP Provider does not have subscriptions, use WebSockets instead';
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 | export default class HttpProvider implements ProviderInterface {
|
33 | private coder: RpcCoder;
|
34 | private endpoint: string;
|
35 | private l: Logger;
|
36 |
|
37 | constructor (endpoint: string) {
|
38 | assert(/^(https|http):\/\//.test(endpoint), `Endpoint should start with 'http://', received '${endpoint}'`);
|
39 |
|
40 | this.coder = coder();
|
41 | this.endpoint = endpoint;
|
42 | this.l = logger('api-http');
|
43 | }
|
44 |
|
45 | |
46 |
|
47 |
|
48 |
|
49 | isConnected (): boolean {
|
50 | return true;
|
51 | }
|
52 |
|
53 | |
54 |
|
55 |
|
56 | on (type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void {
|
57 | this.l.error(`HTTP Provider does not have 'on' emitters, use WebSockets instead`);
|
58 | }
|
59 |
|
60 | async send (method: string, params: Array<any>): Promise<any> {
|
61 | const body = this.coder.encodeJson(method, params);
|
62 | const response = await fetch(this.endpoint, {
|
63 | body,
|
64 | headers: {
|
65 | 'Accept': 'application/json',
|
66 | 'Content-Length': `${body.length}`,
|
67 | 'Content-Type': 'application/json'
|
68 | },
|
69 | method: 'POST'
|
70 | });
|
71 |
|
72 | assert(response.ok, `[${response.status}]: ${response.statusText}`);
|
73 |
|
74 | const result = await response.json();
|
75 |
|
76 | return this.coder.decodeResponse(result);
|
77 | }
|
78 |
|
79 | |
80 |
|
81 |
|
82 | async subscribe (types: string, method: string, params: Array<any>, cb: ProviderInterface$Callback): Promise<number> {
|
83 | this.l.error(ERROR_SUBSCRIBE);
|
84 |
|
85 | throw new Error(ERROR_SUBSCRIBE);
|
86 | }
|
87 |
|
88 | |
89 |
|
90 |
|
91 | async unsubscribe (type: string, method: string, id: number): Promise<boolean> {
|
92 | this.l.error(ERROR_SUBSCRIBE);
|
93 |
|
94 | throw new Error(ERROR_SUBSCRIBE);
|
95 | }
|
96 | }
|