Skip to content

Instantly share code, notes, and snippets.

@gaearon
Last active January 2, 2016 04:59
Show Gist options
  • Save gaearon/8253777 to your computer and use it in GitHub Desktop.
Save gaearon/8253777 to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose')
, Q = require('q')
, Wallet = mongoose.model('Wallet')
, _ = require('underscore')
, bitcoin = require('bitcoin');
function connect(coin) {
return new bitcoin.Client({
host: coin.host,
port: coin.port,
user: coin.user,
pass: coin.pass,
});
}
var wallet = Wallet.find(),
exec = Q.denodeify(wallet.exec.bind(wallet));
function getServiceBalance(service, userID) {
var client = connect(service)
, cmd = Q.denodeify(client.cmd.bind(client))
, getBalance = Q.denodeify(client.getBalance.bind(client))
, getAddressesByAccount = Q.denodeify(client.getAddressesByAccount.bind(client));
// We're going to fill this in step by step...
var result = {
name: service.name,
display: service.display,
abr: service.abr
};
return getBalance(userID, 6)
.then(function (balance) {
result.balance = balance;
console.log("Balance:" + balance);
console.log("User ID: " + userID);
return getAddressesByAccount(userID);
})
.then(function (addresses) {
console.log("Addresses:", address);
if (!_.isArray(addresses)) {
// Throwing errors inside `then` is fine: they will get caught in `catch` below
throw new Error('Could not get addresses array');
}
// For each address, call getreceivedbyaddress and gather results in array
return Q.all(_.map(addresses, function (address) {
return cmd('getreceivedbyaddress', address, 6).then(function (received) {
return [address, received];
});
}));
}).then(function (addressesReceived) {
result.address = _.object(addressesReceived);
}).catch(function (err) {
// Here's the catch method--the *one and only* place all errors propagate to.
console.log(err);
result.balance = 'Offline';
result.address = 'Offline';
}).thenResolve(result);
}
exports.all = function (req, res) {
if (!req.isAuthenticated()){
res.redirect('login');
} else {
exec().then(function (services) {
if (!services) {
throw new Error('Failed to load any Services');
}
var promises = _.map(services, function (service) {
return getServiceBalance(service, req.user._id);
});
return Q.all(promises);
}).then(function (serviceBalances) {
req.breadcrumbs('Services', '/services/all');
res.render('services/index', {
title: 'Services',
icon: 'iconfa-cog',
summary: 'Services information',
services: serviceBalances,
path : req.path,
breadcrumbs: req.breadcrumbs(),
udata : req.session.user
});
}).catch(function (err) {
console.log('Error:', err);
// TODO: render an error message?
}).done();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment