From 0700cd1cd98e6b97d7f0199e9aa8014f487b52c7 Mon Sep 17 00:00:00 2001 From: Matias Alejo Garcia Date: Thu, 9 Jan 2014 20:24:14 -0300 Subject: [PATCH] simple Address model class created --- app/models/Address.js | 94 +++++++++++++++++++++++++++++++++++++++++++ test/model/addr.js | 2 +- 2 files changed, 95 insertions(+), 1 deletion(-) create mode 100644 app/models/Address.js diff --git a/app/models/Address.js b/app/models/Address.js new file mode 100644 index 0000000..68a2979 --- /dev/null +++ b/app/models/Address.js @@ -0,0 +1,94 @@ +'use strict'; + +/** + * Module dependencies. + */ +var mongoose = require('mongoose'), + Schema = mongoose.Schema, + RpcClient = require('bitcore/RpcClient').class(), + config = require('../../config/config') + ; + +/** + * Block Schema + */ +var AddressSchema = new Schema({ + + // For now we keep this as short as possible + // More fields will be propably added as we move + // forward with the UX + addr: { + type: String, + index: true, + unique: true, + }, + balance: Number, + totalReceived: Number, + totalSent: Number, + inTransactions: [String], +}); + + +/** + * Validations + */ + +/* +AddressSchema.path('title').validate(function(title) { + return title.length; +},'Title cannot be blank'); +*/ + +/** + * Statics + */ + +AddressSchema.statics.load = function(id, cb) { + this.findOne({ + _id: id + }).exec(cb); +}; + + +AddressSchema.statics.fromAddr = function(hash, cb) { + this.findOne({ + hash: hash, + }).exec(cb); +}; + + +AddressSchema.statics.fromAddrWithInfo = function(hash, cb) { + this.fromHash(hash, function(err, block) { + if (err) return cb(err); + if (!block) { return cb(new Error('Block not found')); } + + block.getInfo(function(err) { return cb(err,block); } ); + }); +}; + + + +// TODO: Can we store the rpc instance in the Block object? +AddressSchema.methods.getInfo = function (next) { + + var that = this; + var rpc = new RpcClient(config.bitcoind); + + rpc.getBlock(this.hash, function(err, blockInfo) { + if (err) return next(err); + + /* + * Not sure this is the right way to do it. + * Any other way to lazy load a property in a mongoose object? + */ + + that.info = blockInfo.result; + + //console.log("THAT", that); + return next(null, that.info); + }); +}; + + + +module.exports = mongoose.model('Address', AddressSchema); diff --git a/test/model/addr.js b/test/model/addr.js index 815f7bc..ccb560e 100644 --- a/test/model/addr.js +++ b/test/model/addr.js @@ -89,7 +89,7 @@ describe('Address fromAddrWithInfo', function(){ addrs.forEach( function(t) { it('should retrieve the correct info for' + t.addr, function(done) { - Addr.fromHashWithInfo(t.addr, function(err, a) { + Address.fromHashWithInfo(t.addr, function(err, a) { if (err) done(err); assert.equal(t.balance, a.balance, "balance");