diff --git a/.gitignore b/.gitignore index bada20d..aaac872 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,5 @@ debug.log .idea/ isolate*.log dump.rdb -Vagrantfile \ No newline at end of file +Vagrantfile +orbit-db-cache.json diff --git a/src/Cache.js b/src/Cache.js new file mode 100644 index 0000000..3046e07 --- /dev/null +++ b/src/Cache.js @@ -0,0 +1,30 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const filename = 'orbit-db-cache.json'; +let cache = {}; + +class Cache { + static set(key, value) { + cache[key] = value; + fs.writeFile(path.resolve(filename), JSON.stringify(cache, null, 2) + "\n", (err) => { + if (err) throw err; + // console.log('It\'s saved!', path.resolve(filename)); + }); + } + + static get(key) { + return cache[key]; + } + + static loadCache() { + if(fs.existsSync(path.resolve(filename))) { + console.log('Load cache from', path.resolve(filename)); + cache = JSON.parse(fs.readFileSync(path.resolve(filename))); + } + } +} + +module.exports = Cache; \ No newline at end of file diff --git a/src/OrbitDB.js b/src/OrbitDB.js index bd53fb9..e50fe28 100644 --- a/src/OrbitDB.js +++ b/src/OrbitDB.js @@ -7,6 +7,7 @@ const await = require('asyncawait/await'); const Log = require('ipfs-log'); const DBOperation = require('./db/Operation'); const Post = require('./post/Post'); +const Cache = require('./Cache'); class OrbitDB { constructor(ipfs) { @@ -20,6 +21,9 @@ class OrbitDB { this.user = user; this._logs[channel] = await(Log.create(this._ipfs, this.user.username)); this.events[channel] = new EventEmitter(); + + Cache.loadCache(); + this.sync(channel, Cache.get(channel)); } sync(channel, hash) { @@ -33,9 +37,10 @@ class OrbitDB { // Only emit the event if something was added const joinedCount = (this._logs[channel].items.length - oldCount); - if(joinedCount > 0) + if(joinedCount > 0) { this.events[channel].emit('sync', channel, hash); - + Cache.set(channel, hash); + } } this.events[channel].emit('loaded', channel, hash); // }), 3000); @@ -120,6 +125,7 @@ class OrbitDB { const hash = await(DBOperation.create(this._ipfs, this._logs[channel], this.user, operation, key, value)); const listHash = await(Log.getIpfsHash(this._ipfs, this._logs[channel])); this.events[channel].emit('write', channel, listHash); + Cache.set(channel, listHash); return hash; }