This repository has been archived by the owner on Jul 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (67 loc) · 2.04 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
var events = require('events')
var hyperlog = require('hyperlog')
var collect = require('stream-collector')
var lexint = require('lexicographic-integer')
var pump = require('pump')
var protobuf = require('protocol-buffers')
var prefixer = require('sublevel-prefixer')
var subleveldown = require('subleveldown')
var through = require('through2')
var fs = require('fs')
var messages = protobuf(fs.readFileSync(__dirname + '/schema.proto', 'utf-8'))
var prefix = prefixer()
module.exports = function (db) {
var that = new events.EventEmitter()
var essids = subleveldown(db, 'essid')
var meta = subleveldown(db, 'meta')
var log = hyperlog(subleveldown(db, 'log'), {
valueEncoding: messages.Wifi
})
meta.get('change', function (_, change) {
change = parseInt(change || 0, 10)
pump(log.createReadStream({since: change, live: true}), through.obj(write), onerror)
function onerror (err) {
that.emit('error', err || new Error('Change feed closed'))
}
function write (data, enc, cb) {
var batch = [{
type: 'put',
key: prefix('essid', data.value.essid + '!' + lexint.pack(data.change, 'hex')),
value: data.value.password
}, {
type: 'put',
key: prefix('meta', 'change'),
value: '' + data.change
}]
db.batch(batch, function (err) {
if (err) return cb(err)
that.emit('add')
cb()
})
}
})
that.createReadStream = function (opts) {
return log.createReadStream(opts)
}
that.get = function (essid, cb) {
var rs = essids.createValueStream({
gt: essid + '!',
lt: essid + '!~',
valueEncoding: 'utf-8'
})
return collect(rs, cb)
}
that.add = function (essid, password, cb) {
log.append({essid: essid, password: password}, cb)
}
that.replicate = function (opts) {
return log.replicate({live: true})
}
return that
}
if (require.main !== module) return
var db = module.exports(require('memdb')())
db.add('an-essid', 'secure')
db.once('add', function () {
db.get('an-essid', console.log)
})