From 7ba32bb0ed95d6149ce248bdf828b306117d7f79 Mon Sep 17 00:00:00 2001 From: bumi Date: Sat, 21 Apr 2018 16:45:04 +0200 Subject: [PATCH] Extract healthcheck into its own class This moves the whole checks if everything is running into its own class and is no longer inside the different functions. Makes the functions smaller and the healthcheck can be used from the client only if wanted/needed. --- lib/kredits.js | 18 +++++++++--------- lib/utils/healthcheck.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 9 deletions(-) create mode 100644 lib/utils/healthcheck.js diff --git a/lib/kredits.js b/lib/kredits.js index 9062d69..5ec030a 100644 --- a/lib/kredits.js +++ b/lib/kredits.js @@ -1,6 +1,8 @@ const ethers = require('ethers'); const RSVP = require('rsvp'); +const Healthcheck = require('./utils/healthcheck'); + const ABIS = { Contributors: require('./abis/Contributors.json'), Operator: require('./abis/Operator.json'), @@ -49,15 +51,9 @@ class Kredits { static setup(provider, signer, ipfsConfig = null) { console.log('Kredits.setup() is deprecated use new Kredits().init() instead'); let ipfs = new IPFS(ipfsConfig); - - return ipfs._ipfsAPI.id().catch((error) => { - throw new Error(`IPFS node not available; config: ${JSON.stringify(ipfsConfig)} - ${error.message}`); - }).then(() => { - - return new Kredits(provider, signer).init().then((kredits) => { - kredits.ipfs = ipfs; - return kredits; - }); + return new Kredits(provider, signer).init().then((kredits) => { + kredits.ipfs = ipfs; + return kredits; }); } @@ -98,6 +94,10 @@ class Kredits { return this.contracts[name]; } + + healthcheck() { + return new Healthcheck(this).check(); + } } module.exports = Kredits; diff --git a/lib/utils/healthcheck.js b/lib/utils/healthcheck.js new file mode 100644 index 0000000..8a76c58 --- /dev/null +++ b/lib/utils/healthcheck.js @@ -0,0 +1,28 @@ +class Healthcheck { + constructor(kredits) { + this.kredits = kredits; + } + + check() { + return this.kredits.ipfs._ipfsAPI.id() + .catch((error) => { + throw new Error(`IPFS node not available; config: ${JSON.stringify(this.kredits.ipfs.config)} - ${error.message}`); + }) + .then(() => { + let promises = Object.keys(this.kredits.contracts).map((name) => { + let contractWrapper = this.kredits.contracts[name]; + return this.kredits.provider.getCode(contractWrapper.contract.address).then((code) => { + // not sure if we always get the same return value if the code is not available + // so checking if it is < 5 long + if (code === '0x00' || code.length < 5) { + throw new Error(`Contract for: ${name} not found at ${contractWrapper.contract.address} on network ${this.kredits.provider.chainId}`); + } + return true; + }); + }); + return Promise.all(promises); + }); + } +} + +module.exports = Healthcheck;