-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
67 lines (60 loc) · 1.83 KB
/
Copy pathindex.js
File metadata and controls
67 lines (60 loc) · 1.83 KB
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
var stringKey = require('dwebx-encoding').toStr
// var path = require('path')
var xtend = Object.assign
var toiletdb = require('toiletdb')
module.exports = function (archive, opts) {
if (!opts) opts = {}
var db = toiletdb({ name: '/dwebx.json', fs: archive })
var fileDb = opts.file ? toiletdb(opts.file) : null
var that = {
read: function (cb) {
archive.stat('/dwebx.json', function (err, stat) {
if (err) return cb(err)
db.read(cb)
})
},
write: function (key, val, cb) {
if (typeof val === 'function') cb = val
if (!archive.writable) {
return process.nextTick(cb, new Error('Archive not writable'))
}
if (typeof key === 'object') return writeAll(key, cb)
// TODO: validate things
if (!fileDb) return db.write(key, val, cb)
// write to file then archive
// TODO: use ddrive indexing false option, need to talk to mafintosh about
// https://botbot.me/freenode/dwebx/2017-05-12/?msg=85554242&page=3
fileDb.write(key, val, function (err) {
if (err) return cb(err)
db.write(key, val, cb)
})
},
delete: db.delete,
create: function (data, cb) {
if (typeof data === 'function') return that.create(null, data)
if (!archive.writable) {
return process.nextTick(cb, new Error('Archive not writable'))
}
data = xtend(getdefaults(), data)
that.write(data, cb)
}
}
return that
function getdefaults () {
return {
title: '',
description: '',
url: 'dwebx://' + stringKey(archive.key)
}
}
function writeAll (data, cb) {
var keys = Object.keys(data)
var pending = keys.length
keys.map(function (key) {
that.write(key, data[key], function (err) {
if (err) return cb(err)
if (!--pending) return cb()
})
})
}
}