-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
57 lines (49 loc) · 1.25 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
var AutoIndex = require('level-auto-index')
var access = require('deep-access')
var sub = require('subleveldown')
module.exports = Idx
function Idx (db, idb, opts) {
if (!(this instanceof Idx)) return new Idx(db, idb, opts)
if (!opts) opts = {}
this.db = db
this.db.methods = this.db.methods || {}
this.idb = idb
this.keyEncoding = opts.keyEncoding || 'utf8'
this.keyFn = opts.keyEncoding && opts.keyEncoding.type === 'bytewise-core'
? keyFns.bytewise
: keyFns.utf8
}
var keyFns = {
utf8: function (segs) { return segs.join('!') },
bytewise: function (segs) { return segs }
}
Idx.prototype.by = function (name, props) {
if (!Array.isArray(props)) props = [props]
var self = this
var autoIdx = AutoIndex(
this.db,
sub(this.idb, name, {
valueEncoding: this.db.options.keyEncoding,
keyEncoding: this.keyEncoding
}),
reducer
)
function reducer (value) {
var segs = []
props.forEach(function (prop) {
try {
var seg = access(value, prop)
} catch (e) {
return
}
segs.push(seg)
})
return self.keyFn(segs)
}
this.db['by' + name] = autoIdx
this.db.methods['by' + name] = {
type: 'object',
methods: autoIdx.manifest.methods
}
return this
}