Skip to content

Instantly share code, notes, and snippets.

@aj0strow
Created November 14, 2018 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aj0strow/45f2a83e55f8e1fc08a9864fb13e7484 to your computer and use it in GitHub Desktop.
Save aj0strow/45f2a83e55f8e1fc08a9864fb13e7484 to your computer and use it in GitHub Desktop.
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