Created
November 14, 2018 18:21
-
-
Save aj0strow/45f2a83e55f8e1fc08a9864fb13e7484 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment