UNPKG

2.86 kBJavaScriptView Raw
1"use strict";
2
3var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
5Object.defineProperty(exports, "__esModule", {
6 value: true
7});
8exports.default = void 0;
9
10require("./polyfill");
11
12var _assert = _interopRequireDefault(require("@polkadot/util/assert"));
13
14var _logger = _interopRequireDefault(require("@polkadot/util/logger"));
15
16var _json = _interopRequireDefault(require("../coder/json"));
17
18// Copyright 2017-2018 @polkadot/api-provider authors & contributors
19// This software may be modified and distributed under the terms
20// of the ISC license. See the LICENSE file for details.
21const ERROR_SUBSCRIBE = 'HTTP Provider does not have subscriptions, use WebSockets instead';
22/**
23 * The HTTP Provider allows sending requests using HTTP. it does not support subscriptions
24 * so you won´t be able to listen to events such as new blocks or balance changes.
25 * It is usually preferrable using the [[WsProvider]].
26 *
27 * @example
28 * import createApi from '@polkadot/api';
29 * import WsProvider from '@polkadot/api-provider/ws';
30 *
31 * const provider = new WsProvider('http://127.0.0.1:9933');
32 * const api = createApi(provider);
33 *
34 * @see [[WsProvider]]
35 */
36
37class HttpProvider {
38 constructor(endpoint) {
39 this.coder = void 0;
40 this.endpoint = void 0;
41 this.l = void 0;
42 (0, _assert.default)(/^(https|http):\/\//.test(endpoint), `Endpoint should start with 'http://', received '${endpoint}'`);
43 this.coder = (0, _json.default)();
44 this.endpoint = endpoint;
45 this.l = (0, _logger.default)('api-http');
46 }
47 /**
48 * Whether the node is connected or not.
49 * @return {boolean} true if connected
50 */
51
52
53 isConnected() {
54 return true;
55 }
56 /**
57 * Events are not supported with the HttpProvider, see [[WsProvider]].
58 */
59
60
61 on(type, sub) {
62 this.l.error(`HTTP Provider does not have 'on' emitters, use WebSockets instead`);
63 }
64
65 async send(method, params) {
66 const body = this.coder.encodeJson(method, params);
67 const response = await fetch(this.endpoint, {
68 body,
69 headers: {
70 'Accept': 'application/json',
71 'Content-Length': `${body.length}`,
72 'Content-Type': 'application/json'
73 },
74 method: 'POST'
75 });
76 (0, _assert.default)(response.ok, `[${response.status}]: ${response.statusText}`);
77 const result = await response.json();
78 return this.coder.decodeResponse(result);
79 }
80 /**
81 * Subscriptions are not supported with the HttpProvider, see [[WsProvider]].
82 */
83
84
85 async subscribe(types, method, params, cb) {
86 this.l.error(ERROR_SUBSCRIBE);
87 throw new Error(ERROR_SUBSCRIBE);
88 }
89 /**
90 * Subscriptions are not supported with the HttpProvider, see [[WsProvider]].
91 */
92
93
94 async unsubscribe(type, method, id) {
95 this.l.error(ERROR_SUBSCRIBE);
96 throw new Error(ERROR_SUBSCRIBE);
97 }
98
99}
100
101exports.default = HttpProvider;
\No newline at end of file