Skip to content

Instantly share code, notes, and snippets.

@aj0strow
Created November 14, 2018 18:21
Show Gist options
  • Select an option

  • Save aj0strow/45f2a83e55f8e1fc08a9864fb13e7484 to your computer and use it in GitHub Desktop.

Select an option

Save aj0strow/45f2a83e55f8e1fc08a9864fb13e7484 to your computer and use it in GitHub Desktop.

Revisions

  1. aj0strow created this gist Nov 14, 2018.
    44 changes: 44 additions & 0 deletions iconHttpProvider.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    const axios = require("axios")

    class HttpProvider {
    constructor(url) {
    this.url = url
    this.id = 0
    this.jsonrpc = '2.0'
    }

    // Call JSON RPC method. Get back { id, result } or { id, error }.
    async call(method, params) {
    const request = {
    jsonrpc: this.jsonrpc,
    id: ++this.id,
    method,
    params
    }
    const body = this.jsonStringify(request)
    try {
    const response = await axios.post(this.url, body)
    return response.data
    } catch (error) {
    if (this.isAxios(error)) {
    return error.response.data
    }
    throw error
    }
    }

    isAxios(error) {
    const keys = Object.keys(error)
    keys.sort()
    return keys[0] === 'config' && keys[1] === 'request' && keys[2] === 'response'
    }

    jsonStringify(request) {
    return JSON.stringify(request, (key, value) => {
    if (value) {
    return value
    }
    return undefined
    })
    }
    }