From 8e776bc11e74721369780b78adf21c6456d4cb31 Mon Sep 17 00:00:00 2001 From: Roman Lisagor Date: Tue, 24 Jan 2017 14:36:54 -0800 Subject: [PATCH] Use async account fetch instead of sync This allows TestRPC to run in the same node process as the loopback app --- index.js | 2 ++ lib/web3.js | 22 ++++++++++++++-------- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/index.js b/index.js index 7456d36..ce61f61 100644 --- a/index.js +++ b/index.js @@ -5,5 +5,7 @@ var Web3 = require('./lib/web3'); exports.initialize = function(dataSource, cb) { var settings = dataSource.settings; var connector = new Web3(settings); + connector.connect(cb); + dataSource.connector = connector; }; diff --git a/lib/web3.js b/lib/web3.js index c09f6c7..8169ace 100644 --- a/lib/web3.js +++ b/lib/web3.js @@ -13,18 +13,24 @@ function Web3Connector(settings) { this.settings = settings; const url = settings.url || 'http://localhost:8545'; - const web3 = new Web3(new Web3.providers.HttpProvider(url)); - - if (web3.eth.accounts[0]) { - web3.eth.defaultAccount = web3.eth.accounts[0]; - } else { - throw "error : can not connect to rpc server - please check datasources.json" - } - this.web3 = web3; + this.web3 = new Web3(new Web3.providers.HttpProvider(url)); } Web3Connector.prototype.DataAccessObject = Web3DAO; +Web3Connector.prototype.connect = function(cb) { + const web3 = this.web3; + + web3.eth.getAccounts(function(err, accounts) { + if (err) { + return cb(err); + } + + web3.eth.defaultAccount = accounts[0]; + cb(); + }); +} + Web3Connector.prototype.define = function(modelData) { var web3 = this.web3; var model = modelData.model;