Add naive local cache

This commit is contained in:
haad 2016-03-22 08:28:52 +01:00
parent 872ae19944
commit 070f289940
3 changed files with 40 additions and 3 deletions

3
.gitignore vendored
View File

@ -5,4 +5,5 @@ debug.log
.idea/
isolate*.log
dump.rdb
Vagrantfile
Vagrantfile
orbit-db-cache.json

30
src/Cache.js Normal file
View File

@ -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;

View File

@ -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;
}