diff --git a/server/lib/api/address.js b/server/lib/api/address.js index edcbdcd..d7594f1 100644 --- a/server/lib/api/address.js +++ b/server/lib/api/address.js @@ -1,7 +1,10 @@ -const Block = require('../../models/block.js'); -const logger = require('../logger'); +const Block = require('../../models/block.js'); +const logger = require('../logger'); const request = require('request'); -const config = require('../../config'); +const config = require('../../config'); +const db = require('../db'); + +console.log(db); const MAX_BLOCKS = 200; diff --git a/server/lib/db/blocks.js b/server/lib/db/blocks.js new file mode 100644 index 0000000..cdc200c --- /dev/null +++ b/server/lib/db/blocks.js @@ -0,0 +1,57 @@ +const Block = require('../../models/block.js'); +const logger = require('../logger'); +const config = require('../../config'); + +// move to config +const MAX_BLOCKS = 200; +const blockTemplate = new Block(); + +function getBlocks(params, options, limit, cb) { + const defaultOptions = { _id: 0 }; + + Object.assign(defaultOptions, options); + + if (!Number.isInteger(limit)) { + limit = MAX_BLOCKS; + } + + if (limit > MAX_BLOCKS) { + limit = MAX_BLOCKS; + } + + Block.find( + params, + defaultOptions, + (err, blocks) => { + if (err) { + logger.log('error', + `getBlocks: ${err}`); + return cb(err); + } + if (blocks.length > 0) { + return cb(null, blocks); + } + return cb(null, [blockTemplate]); + }) + .sort({ height: -1 }) + .limit(limit); +} + +function getBlock(params, options, limit, cb) { + getBlocks(params, options, limit, (err, blocks) => { + if (err) { + logger.log('error', + `getBlock: ${err}`); + return cb(err); + } + if (blocks.length > 0) { + return cb(null, blocks[0]); + } + return cb(null, blockTemplate); + }); +} + +module.exports = { + getBlock, + getBlocks, +}; diff --git a/server/lib/db/index.js b/server/lib/db/index.js index 43f325f..f808838 100644 --- a/server/lib/db/index.js +++ b/server/lib/db/index.js @@ -1,5 +1,6 @@ const mongoose = require('mongoose'); const logger = require('../logger'); +const Blocks = require('./blocks'); mongoose.connection.on('error', (err) => { logger.log('error', @@ -7,4 +8,8 @@ mongoose.connection.on('error', (err) => { ${err}`); }); -module.exports = mongoose; +module.exports = { + connect: mongoose.connect, + connection: mongoose.connection, + Blocks, +};