2014-10-22 09:38:33 +00:00
|
|
|
(function () {
|
|
|
|
var HttpProvider = function (host) {
|
|
|
|
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);
|
|
|
|
|
2014-10-22 14:12:41 +00:00
|
|
|
return {
|
2014-10-22 09:38:33 +00:00
|
|
|
_id: object.id,
|
|
|
|
data: object.result
|
2014-10-22 14:12:41 +00:00
|
|
|
};
|
2014-10-22 09:38:33 +00:00
|
|
|
};
|
|
|
|
|
2014-10-23 12:11:57 +00:00
|
|
|
HttpProvider.prototype.sendRequest = function (payload, cb) {
|
2014-10-22 09:38:33 +00: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 12:11:57 +00:00
|
|
|
if (request.readyState === 4 && cb) {
|
|
|
|
cb(request);
|
2014-10-22 09:38:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2014-10-23 12:11:57 +00:00
|
|
|
HttpProvider.prototype.send = function (payload) {
|
|
|
|
var self = this;
|
|
|
|
this.sendRequest(payload, function (request) {
|
|
|
|
self.handlers.forEach(function (handler) {
|
|
|
|
handler.call(self, formatJsonRpcMessage(request.responseText));
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
HttpProvider.prototype.poll = function (payload, id) {
|
|
|
|
var self = this;
|
|
|
|
this.sendRequest(payload, function (request) {
|
|
|
|
var parsed = JSON.parse(request.responseText);
|
|
|
|
if (!parsed.result) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
self.handlers.forEach(function (handler) {
|
|
|
|
handler.call(self, {_event: "messages", data: id});
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2014-10-22 09:38:33 +00:00
|
|
|
Object.defineProperty(HttpProvider.prototype, "onmessage", {
|
|
|
|
set: function (handler) {
|
|
|
|
this.handlers.push(handler);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
if (typeof(web3) !== "undefined" && web3.providers !== undefined) {
|
|
|
|
web3.providers.HttpProvider = HttpProvider;
|
|
|
|
}
|
|
|
|
})();
|