-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
104 lines (79 loc) · 1.9 KB
/
client.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
var WriteOperation = function (ws, key, value) {
this.value = value;
this.key = key;
this.id = new Date().getTime();
this.data = {
key: this.key,
value: this.value,
id: this.id
};
this.callbacks = {
'success': [],
'fail': []
};
var cb = function (d) {
if (d.id !== id) {
return;
}
this.callbacks['success'].forEach(function (cb) {
cb();
});
ws.removeListener(cb);
}.bind(this);
ws.on('confirm', cb);
};
WriteOperation.prototype.commit = function () {
ws.emit('write', this.data);
};
WriteOperation.prototype.success = function (cb) {
this.callbacks['success'].push(cb);
};
WriteOperation.prototype.fail = function () {
this.callbacks['fail'].push(cb);
};
var ReadOperation = function (ws, key) {
this.callbacks = {
'success': []
};
ws.on('read', function (data) {
if (data.key === key) {
this.callbacks.success.forEach(function (cb) {
cb(data.value);
});
}
});
};
ReadOperation.prototype.success = function (cb) {
this.callbacks['success'].push(cb);
};
var KeePee = function (ws) {
ws.on('keys', function (keys) {
for (var x in keys) {
var ro = this.read(keys[x]);
ro.success(function (d) {
this.data[d.key] = d;
}.bind(this));
}
}.bind(this));
ws.on('write', function (d) {
this.data[d.key] = d;
ws.emit('confirm', d);
});
ws.on('read', function (key) {
ws.emit('read', this.data[key]);
});
ws.emit('keys');
this.data = {};
this.ws = ws;
};
KeePee.prototype.write = function (key, value) {
var wo = new WriteOperation(this.ws, key, value);
wo.success(function () {
this.data[key] = wo.data;
}.bind(this));
return wo;
};
KeePee.prototype.read = function (key) {
var ro = new ReadOperation(this.ws, key);
return ro;
};