Using web3.js
version 1(beta) and using the WebsocketProvider to make a connection via
const Web3 = require('web3')
const web3 = new Web3('ws://localhost:8546')
const provider = web3.providers.WebsocketProvider
const { connection } = provider
==> connection
is undefined
looking at the source for the WebsocketProvider
I can see it's got a connection
object
function WebsocketProvider(url) {
var _this = this;
this.responseCallbacks = {};
this.notificationCallbacks = [];
this.connection = new Ws(url);
this.addDefaultEvents();
// LISTEN FOR CONNECTION RESPONSES
this.connection.onmessage = function(e) {
/*jshint maxcomplexity: 6 */
var data = (typeof e.data === 'string') ? e.data : '';
_this._parseResponse(data).forEach(function(result){
var id = null;
// get the id which matches the returned id
if(_.isArray(result)) {
result.forEach(function(load){
if(_this.responseCallbacks[load.id])
id = load.id;
});
} else {
id = result.id;
}
// notification
if(!id && result.method.indexOf('_subscription') !== -1) {
_this.notificationCallbacks.forEach(function(callback){
if(_.isFunction(callback))
callback(null, result);
});
// fire the callback
} else if(_this.responseCallbacks[id]) {
_this.responseCallbacks[id](null, result);
delete _this.responseCallbacks[id];
}
});
};
}
Curiously I can't actually find the source code for this in GitHub, the above comes by logging web3.providers.WebsocketProvider
Questions
- At what point is the connection actually made,
- how can I expose it such that I can attach error and other handlers to make a more reliable connection, and
- Where is the source code for this, given it's nowhere to be found in github.com/ethereum/web3.js