diff --git a/package.json b/package.json index 95c6c6b03e..cd2cb1c2e2 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ "is-ipfs": "^0.2.1", "isstream": "^0.1.2", "multiaddr": "^2.0.3", + "lru-cache": "^4.0.1", "multipart-stream": "^2.0.1", "ndjson": "^1.4.3", "once": "^1.4.0", diff --git a/src/api/object.js b/src/api/object.js index 4841c8330b..1d77bcd74b 100644 --- a/src/api/object.js +++ b/src/api/object.js @@ -7,6 +7,12 @@ const promisify = require('promisify-es6') const bs58 = require('bs58') const bl = require('bl') const cleanMultihash = require('../clean-multihash') +const LRU = require('lru-cache') +const lruOptions = { + max: 128 +} + +const cache = LRU(lruOptions) module.exports = (send) => { const api = { @@ -15,6 +21,7 @@ module.exports = (send) => { callback = options options = {} } + if (!options) { options = {} } @@ -25,6 +32,12 @@ module.exports = (send) => { return callback(err) } + const node = cache.get(multihash) + + if (node) { + return callback(null, node) + } + send({ path: 'object/get', args: multihash @@ -38,9 +51,12 @@ module.exports = (send) => { return new DAGLink(l.Name, l.Size, new Buffer(bs58.decode(l.Hash))) })) + cache.set(multihash, node) + callback(null, node) }) }), + put: promisify((obj, options, callback) => { if (typeof options === 'function') { callback = options @@ -122,6 +138,8 @@ module.exports = (send) => { return callback(new Error('Stored object was different from constructed object')) } + cache.set(result.Hash, node) + callback(null, node) }) } @@ -142,6 +160,12 @@ module.exports = (send) => { return callback(err) } + const node = cache.get(multihash) + + if (node) { + return callback(null, node.data) + } + send({ path: 'object/data', args: multihash @@ -172,6 +196,12 @@ module.exports = (send) => { return callback(err) } + const node = cache.get(multihash) + + if (node) { + return callback(null, node.links) + } + send({ path: 'object/links', args: multihash