All files / src/util httpProvider.js

92.5% Statements 111/120
89.85% Branches 62/69
92% Functions 23/25
92.37% Lines 109/118

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267            22x         22x 22x 22x   22x       22x 22x 22x 11x 11x 11x 11x 11x                                         59x 59x 59x 59x 59x 1x 1x   1x         58x                 58x 58x   8x   58x         4x 4x 4x                 1x   4x       11x 11x 1x   1x           13x 13x 13x 13x 13x 13x 11x 11x   13x 26x   13x                     11x 11x 11x   11x   10x     10x 10x   2x 2x   8x     6x 6x 3x 3x   3x   1x     1x               53x 53x 53x 53x 44x   53x 53x 106x   53x 44x   9x           26x 1x   1x         25x   25x 25x 24x   24x 24x 1x   23x       25x 24x       26x 26x 26x 26x 26x 26x 789x 26x 26x 26x 26x 1x   25x                 26x     26x               3x 3x       2x   1x         2x 2x         1x        
/**
 * @file rpc connection built with http
 * @author atom-yang
 */
import { stringify } from 'query-string';
 
const defaultHeaders = {
  Accept: 'text/plain;v=1.0',
  'Content-Type': 'application/json'
};
 
let RequestLibrary = {};
let RequestLibraryXMLOnly = null;
let isFetch = false;
let NodeHeaders;
if (process.env.RUNTIME_ENV === 'browser') {
  // For browsers use DOM Api XMLHttpRequest
  // serviceworker without window and document, only with self
  // eslint-disable-next-line no-restricted-globals
  const _self = typeof self === 'object' ? self : {};
  const _window = typeof window === 'object' ? window : _self;
  if (typeof _window.XMLHttpRequest !== 'undefined') {
    RequestLibrary = _window.XMLHttpRequest;
    isFetch = false;
  } else Eif (typeof _window.fetch !== 'undefined') {
    RequestLibrary = _window.fetch;
    isFetch = true;
  }
} else E{
  // For node use xmlhttprequest
  // eslint-disable-next-line global-require
  RequestLibraryXMLOnly = require('xmlhttprequest').XMLHttpRequest;
  // eslint-disable-next-line global-require
  const NodeFetch = require('node-fetch');
  RequestLibrary = NodeFetch.default;
  NodeHeaders = NodeFetch.Headers;
  isFetch = true;
}
 
export default class HttpProvider {
  constructor(
    host = 'http://localhost:8545',
    timeout = 8000,
    headers = defaultHeaders,
    // support node-fetch options
    options = {}
  ) {
    this.host = host.replace(/\/$/, '');
    this.timeout = timeout;
    this.headers = {};
    this.options = options;
    if (Array.isArray(headers)) {
      headers.forEach(({ name, value }) => {
        this.headers[name] = value;
      });
      this.headers = {
        ...defaultHeaders,
        ...this.headers
      };
    } else {
      this.headers = {
        ...defaultHeaders,
        ...headers
      };
    }
  }
 
  static formatResponse(response) {
    let result;
    try {
      result = JSON.parse(response);
    } catch (e) {
      result = response;
    }
    return result;
  }
 
  static formatResponseText(request) {
    let result;
    try {
      const parseRequest = request;
      result = {
        status: parseRequest.status,
        error: parseRequest.status === 200 ? 0 : parseRequest.status,
        Error: {
          message: request.statusText
        },
        statusText: request.statusText
      };
    } catch (e) {
      result = request;
    }
    return result;
  }
 
  static timeoutPromise(delay) {
    return new Promise(_resolve => {
      const ids = setTimeout(() => {
        clearTimeout(ids);
        // eslint-disable-next-line prefer-promise-reject-errors
        _resolve({ type: 'timeout' });
      }, delay);
    });
  }
 
  requestSendByFetch(requestConfig, request) {
    const { url, method = 'POST', params = {}, signal } = requestConfig;
    const path = `/api/${url}`.replace(/\/\//g, '/');
    let uri = `${this.host}${path}`.replace();
    const myHeaders = process.env.RUNTIME_ENV === 'browser' ? new Headers() : new NodeHeaders();
    let body = JSON.stringify(params);
    if (method.toUpperCase() === 'GET' || method.toUpperCase() === 'DELETE') {
      uri = Object.keys(params).length > 0 ? `${uri}?${stringify(params)}` : uri;
      body = undefined;
    }
    Object.keys(this.headers).forEach(header => {
      myHeaders.append(header, this.headers[header]);
    });
    return request(uri, {
      ...this.options,
      method: method.toUpperCase(),
      headers: myHeaders,
      body,
      signal
    });
  }
 
  sendAsyncByFetch(requestConfig) {
    const request = RequestLibrary;
    const { timeout } = this;
    const control = typeof AbortController === 'function' ? new AbortController() : {};
    const config = { ...requestConfig, signal: control.signal, credentials: 'omit' };
    // Simulation timeout
    return Promise.race([this.requestSendByFetch(config, request), HttpProvider.timeoutPromise(timeout)]).then(
      result =>
        new Promise((resolve, reject) => {
          // @deprecated unuse timeout=1
          // if (timeout !== 1) {
          try {
            if (result.type === 'timeout') {
              // Cancel timeout request
              if (control.abort) control.abort();
              reject(result);
            } else {
              result
                .text()
                .then(text => {
                  const res = HttpProvider.formatResponse(text);
                  if (result.status !== 200 || !result.ok) {
                    reject(res);
                    return;
                  }
                  resolve(res);
                })
                .catch(err => reject(err));
            }
          } catch (e) {
            reject(e);
          }
          // }
        })
    );
  }
 
  requestSend(requestConfig, request, isAsync = false) {
    const { url, method = 'POST', params = {} } = requestConfig;
    const path = `/api/${url}`.replace(/\/\//g, '/');
    let uri = `${this.host}${path}`.replace();
    if (method.toUpperCase() === 'GET' || method.toUpperCase() === 'DELETE') {
      uri = Object.keys(params).length > 0 ? `${uri}?${stringify(params)}` : uri;
    }
    request.open(method.toUpperCase(), uri, isAsync);
    Object.keys(this.headers).forEach(header => {
      request.setRequestHeader(header, this.headers[header]);
    });
    if (method.toUpperCase() === 'GET' || method.toUpperCase() === 'DELETE') {
      request.send();
    } else {
      request.send(JSON.stringify(params));
    }
  }
 
  send(requestConfig) {
    let request;
    if (isFetch) {
      if (!RequestLibraryXMLOnly) {
        // browser case, Chrome extension v3.
        throw new Error("Can not get XMLHttpRequest, invalid parameter: 'sync'");
      } else E{
        request = new RequestLibraryXMLOnly();
      }
    } else {
      request = new RequestLibrary();
    }
    request.withCredentials = false;
    this.requestSend(requestConfig, request);
    let result = request.responseText;
 
    result = HttpProvider.formatResponse(result);
    if (result.Error) {
      throw result;
    }
    return result;
  }
 
  sendAsync(requestConfig) {
    if (isFetch) return this.sendAsyncByFetch(requestConfig);
    return this.sendAsyncByXMLHttp(requestConfig);
  }
 
  sendAsyncByXMLHttp(requestConfig) {
    const request = RequestLibraryXMLOnly ? new RequestLibraryXMLOnly() : new RequestLibrary();
    request.withCredentials = false;
    request.timeout = this.timeout;
    this.requestSend(requestConfig, request, true);
    return new Promise((resolve, reject) => {
      request.onreadystatechange = () => {
        if (request.readyState === 4 && request.timeout !== 1) {
          let result = request.responseText;
          try {
            result = HttpProvider.formatResponse(result);
            if (request.status !== 200 || result.Error) {
              reject(result);
            } else {
              resolve(result);
            }
          } catch (e) {
            // todo: error handle
            reject(e);
          }
        }
      };
 
      request.onerror = err => {
        reject(err);
      };
      request.ontimeout = err => {
        // todo: timeout error
        reject(err);
      };
    });
  }
 
  isConnected() {
    try {
      this.send({
        method: 'GET',
        url: 'blockChain/chainStatus'
      });
      return true;
    } catch (e) {
      return false;
    }
  }
 
  async isConnectedAsync() {
    try {
      return await this.sendAsyncByFetch({
        method: 'GET',
        url: 'blockChain/chainStatus'
      });
    } catch (e) {
      return false;
    }
  }
}