make it actually work

This commit is contained in:
Friedel Ziegelmayer 2016-10-28 12:30:46 +02:00
parent 5062212494
commit 1b845fd74d
3 changed files with 32 additions and 21 deletions

1
.gitignore vendored
View File

@ -12,3 +12,4 @@ dist/*.map
orbit-db.json
dist/orbitdb.js
orbit-db.cache
ipfs/

View File

@ -19,6 +19,7 @@
"fs-pull-blob-store": "^0.4.1",
"idb-pull-blob-store": "^0.5.1",
"ipfs-log": "^1.5.2",
"lock": "^0.1.3",
"logplease": "^1.2.9",
"orbit-db-counterstore": "0.1.7",
"orbit-db-docstore": "0.0.8",

View File

@ -2,27 +2,31 @@
const pull = require('pull-stream')
const BlobStore = require('fs-pull-blob-store')
const Lock = require('lock')
let filePath
let store
let cache = {}
const lock = new Lock()
class Cache {
static set(key, value) {
return new Promise((resolve, reject) => {
cache[key] = value
if(filePath && store) {
// console.log("write cache:", filePath, JSON.stringify(cache, null, 2))
pull(
pull.values([cache]),
pull.map((v) => JSON.stringify(v, null, 2)),
store.write(filePath, (err) => {
if (err) {
return reject(err)
}
resolve()
})
)
lock(filePath, (release) => {
// console.log("write cache:", filePath, JSON.stringify(cache, null, 2))
pull(
pull.values([cache]),
pull.map((v) => JSON.stringify(v, null, 2)),
store.write(filePath, release((err) => {
if (err) {
return reject(err)
}
resolve()
}))
)
})
} else {
resolve()
}
@ -36,6 +40,8 @@ class Cache {
static loadCache(cacheFile = 'orbit-db.cache') {
cache = {}
store = new BlobStore(cacheFile)
filePath = cacheFile
return new Promise((resolve, reject) => {
// console.log("load cache:", cacheFile)
@ -44,17 +50,20 @@ class Cache {
return resolve()
}
filePath = cacheFile
pull(
store.read(cacheFile),
pull.collect((err, res) => {
if (err) {
return reject(err)
}
lock(cacheFile, (release) => {
pull(
store.read(cacheFile),
pull.collect(release((err, res) => {
if (err) {
return reject(err)
}
resolve(JSON.parse(res[0].toString() || '{}'))
})
)
cache = JSON.parse(Buffer.concat(res).toString() || '{}')
resolve()
}))
)
})
})
})
}