API for blocks v0.1 working!

This commit is contained in:
Matias Alejo Garcia 2014-01-07 09:48:31 -03:00
parent b1a439e688
commit 9feb87ddf2
4 changed files with 51 additions and 15 deletions

33
app/controllers/blocks.js Normal file
View File

@ -0,0 +1,33 @@
'use strict';
var Block = require('../models/Block');
//, _ = require('lodash');
/**
* Module dependencies.
*/
/**
* Find block by hash ...
*/
exports.block = function(req, res, next, hash) {
Block.fromHash(hash, function(err, block) {
if (err) return next(err);
if (!block) return next(new Error('Failed to load block ' + hash));
req.block = block;
next();
});
};
/**
* Show block
*/
exports.show = function(req, res) {
res.jsonp(req.block);
};

View File

@ -11,8 +11,8 @@ var mongoose = require('mongoose'),
* Block Schema
*/
var BlockSchema = new Schema({
hash: {
type: String,
hash: {
type: String,
index: true,
unique: true,
},
@ -27,12 +27,12 @@ var BlockSchema = new Schema({
difficulty: Number,
chainwork: String,
previousblockhash: {
type: String,
type: String,
index: true,
unique: true,
},
nextblockhash: {
type: String,
type: String,
index: true,
unique: true,
},
@ -53,16 +53,16 @@ BlockSchema.path('title').validate(function(title) {
*/
BlockSchema.statics.load = function(id, cb) {
this.findOne({
_id: id
}).exec(cb);
this.findOne({
_id: id
}).exec(cb);
};
BlockSchema.statics.fromHash = function(hash, cb) {
this.findOne({
hash: hash,
}).exec(cb);
this.findOne({
hash: hash,
}).exec(cb);
};
module.exports = mongoose.model('Block', BlockSchema);

View File

@ -8,7 +8,10 @@ module.exports = function(app) {
//Block routes
var blocks = require('model/app/controllers/blocks');
app.get('/block/:block_hash', blocks.show);
var blocks = require('../app/controllers/blocks');
app.get('/block/:blockHash', blocks.show);
app.param('blockHash', blocks.block);
};

View File

@ -40,7 +40,7 @@ function getNextBlock(blockHash,cb) {
return cb(err);
}
return getNextBlock(blockInfo.result.nextblockhash);
return getNextBlock(blockInfo.result.nextblockhash, cb);
});
});
@ -49,7 +49,7 @@ function getNextBlock(blockHash,cb) {
function syncBlocks(network, cb) {
Block.findOne({}, {}, { sort: { 'height' : -1 } }, function(err, block) {
Block.findOne({}, {}, { sort: { 'confirmations' : 1 } }, function(err, block) {
if (err) {
return cb(err);
}
@ -63,7 +63,7 @@ function syncBlocks(network, cb) {
;
console.log('Starting at hash' + nextHash);
console.log('Starting at hash: ' + nextHash);
getNextBlock(nextHash, cb);
});
}