This repository has been archived by the owner on Jan 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
108 lines (96 loc) · 2.4 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const stringKey = require('dat-encoding').toStr
const xtend = Object.assign
const toiletdb = require('toiletdb')
module.exports = (...args) => new DatJsonDb(...args)
class DatJsonDb {
constructor (archive, opts) {
if (!opts) opts = {}
this.archive = archive
this.db = toiletdb({ name: '/dat.json', fs: archive })
this.fileDb = opts.file ? toiletdb(opts.file) : null
}
read () {
const self = this
return new Promise((resolve, reject) => {
this.archive.stat('/dat.json', async function (err, stat) {
if (err) return reject(err)
resolve(await self.db.read())
})
})
}
write (key, val) {
return new Promise(async (resolve, reject) => {
if (!this.archive.writable) {
return reject(new Error('Archive not writable'))
}
if (typeof key === 'object') {
try {
await this._writeAll(key)
resolve()
} catch (e) {
reject(e)
}
return
}
// TODO: validate things
if (!this.fileDb) {
try {
await this.db.write(key, val)
resolve()
} catch (e) {
reject(e)
}
return
}
// write to file then archive
// TODO: use hyperdrive indexing false option, need to talk to mafintosh about
// https://botbot.me/freenode/dat/2017-05-12/?msg=85554242&page=3
try {
await this.fileDb.write(key, val)
await this.db.write(key, val)
resolve()
} catch (e) {
reject(e)
}
})
}
async delete (key) {
await this.db.delete(key)
}
create (data) {
return new Promise(async (resolve, reject) => {
if (!this.archive.writable) {
return reject(new Error('Archive not writable'))
}
data = xtend(this.getdefaults(), data)
try {
await this.write(data)
resolve()
} catch (e) {
reject(e)
}
})
}
_writeAll (data, cb) {
const self = this
return new Promise((resolve, reject) => {
const keys = Object.keys(data)
let pending = keys.length
keys.map(async function (key) {
try {
await self.write(key, data[key])
} catch (e) {
reject(e)
}
if (!--pending) return resolve()
})
})
}
getdefaults () {
return {
title: '',
description: '',
url: 'dat://' + stringKey(this.archive.key)
}
}
}