bsc/httprpc.js

71 lines
2.0 KiB
JavaScript
Raw Normal View History

2014-10-22 12:38:33 +03:00
(function () {
2014-10-28 17:53:31 +02:00
var HttpRpcProvider = function (host) {
2014-10-22 12:38:33 +03:00
this.handlers = [];
this.host = host;
};
function formatJsonRpcObject(object) {
return {
jsonrpc: '2.0',
method: object.call,
params: object.args,
id: object._id
}
};
function formatJsonRpcMessage(message) {
var object = JSON.parse(message);
return {
2014-10-22 12:38:33 +03:00
_id: object.id,
data: object.result
};
2014-10-22 12:38:33 +03:00
};
2014-10-28 17:53:31 +02:00
HttpRpcProvider.prototype.sendRequest = function (payload, cb) {
2014-10-22 12:38:33 +03:00
var data = formatJsonRpcObject(payload);
var request = new XMLHttpRequest();
request.open("POST", this.host, true);
request.send(JSON.stringify(data));
request.onreadystatechange = function () {
2014-10-23 15:11:57 +03:00
if (request.readyState === 4 && cb) {
cb(request);
2014-10-22 12:38:33 +03:00
}
}
};
2014-10-28 17:53:31 +02:00
HttpRpcProvider.prototype.send = function (payload) {
2014-10-23 15:11:57 +03:00
var self = this;
this.sendRequest(payload, function (request) {
self.handlers.forEach(function (handler) {
handler.call(self, formatJsonRpcMessage(request.responseText));
});
});
};
2014-10-28 17:53:31 +02:00
HttpRpcProvider.prototype.poll = function (payload, id) {
2014-10-23 15:11:57 +03:00
var self = this;
this.sendRequest(payload, function (request) {
var parsed = JSON.parse(request.responseText);
if (!parsed.result) {
return;
}
self.handlers.forEach(function (handler) {
2014-10-29 15:45:39 +02:00
handler.call(self, {_event: payload.call, _id: id, data: parsed.result});
2014-10-23 15:11:57 +03:00
});
});
};
2014-10-28 17:53:31 +02:00
Object.defineProperty(HttpRpcProvider.prototype, "onmessage", {
2014-10-22 12:38:33 +03:00
set: function (handler) {
this.handlers.push(handler);
}
});
if (typeof(web3) !== "undefined" && web3.providers !== undefined) {
2014-10-28 17:53:31 +02:00
web3.providers.HttpRpcProvider = HttpRpcProvider;
2014-10-22 12:38:33 +03:00
}
})();
2014-10-28 17:53:31 +02:00