-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlevel.js
More file actions
96 lines (76 loc) · 2.4 KB
/
Copy pathlevel.js
File metadata and controls
96 lines (76 loc) · 2.4 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
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
// CAUTION: This adapter does NOT handle encoding. an encoding mechanism like the encoding-down package will need to be included
// Based on localStorage adapter in 05349a5
var Gun = ('undefined' !== typeof window) ? window.Gun : require('../gun');
var debug = false;
Gun.on('opt', function(ctx) {
var opt = ctx.opt;
var ev = this.to;
if (debug) debug.emit('create');
if (ctx.once) return ev.next(ctx);
// Check if the given 'level' argument implements all the components we need
// Intentionally doesn't check for levelup explicitly, to allow different handlers implementing the same api
if (
(!opt.level) ||
('object' !== typeof opt.level) ||
('function' !== typeof opt.level.get) ||
('function' !== typeof opt.level.put)
) {
return;
}
ctx.on('put', function(msg) {
this.to.next(msg);
// Extract data from message
var put = msg.put;
var soul = put['#'];
var key = put['.'];
var val = put[':'];
var state = put['>'];
if (debug) debug.emit('put', soul, val);
// Fetch previous version
opt.level.get(soul, function(err, data) {
if (err && (err.name === 'NotFoundError')) err = undefined;
if (debug && err) debug.emit('error', err);
if (err) return;
// Unclear required transformation
data = Gun.state.ify(data, key, state, val, soul);
// Write into storage
opt.level.put(soul, data, function(err) {
if (err) return;
if (debug) debug.emit('put', soul, val);
// Bail if message was an ack
if (msg['@']) return;
// Send ack back
ctx.on('in', {
'@' : msg['@'],
ok : 0,
});
});
});
});
ctx.on('get', function(msg) {
this.to.next(msg);
// Extract soul from message
var lex = msg.get;
if (!lex || !(soul = lex['#'])) return;
var has = lex['.'];
if (debug) debug.emit('get', soul);
// Fetch data from storage
opt.level.get(soul, function(err, data) {
if (err) return;
// Another unclear transformation
if (data && has) {
data = Gun.state.to(data, has);
}
// Emulate incoming ack
ctx.on('in', {
'@' : msg['#'],
put : Gun.graph.node(data),
});
});
});
});
// Export debug interface
if ('undefined' === typeof window) {
var EventEmitter = require('events').EventEmitter;
module.exports = debug = new EventEmitter();
}