This repository has been archived by the owner on Aug 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
watcher.js
95 lines (82 loc) · 1.98 KB
/
watcher.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
module.exports = function (logger, Watch) {
function Watcher() {
this.child = {}
this.data = {}
this.exists = {}
}
Watcher.prototype.addChildWatch = function (path, cb) {
var watches = this.child[path] || []
watches.push(cb)
this.child[path] = watches
}
Watcher.prototype.addDataWatch = function (path, cb) {
var watches = this.data[path] || []
watches.push(cb)
this.data[path] = watches
}
Watcher.prototype.addExistsWatch = function (path, cb) {
var watches = this.exists[path] || []
watches.push(cb)
this.exists[path] = watches
}
Watcher.prototype.count = function () {
return Object.keys(this.child).length +
Object.keys(this.data).length +
Object.keys(this.exists).length
}
Watcher.prototype.paths = function () {
return {
child: Object.keys(this.child),
data: Object.keys(this.data),
exists: Object.keys(this.exists)
}
}
Watcher.prototype.reset = function () {
this.child = {}
this.data = {}
this.exists = {}
}
Watcher.prototype.fireWatches = function (watches, watch) {
logger.info(
'watch: %s', watch,
'watches', watches.length
)
for (var i = 0; i < watches.length; i++) {
var cb = watches[i]
if (typeof(cb) === 'function') {
cb(watch.toJSON())
}
else {
logger.info('wat', cb)
}
}
}
Watcher.prototype.trigger = function (watch) {
var path = watch.path
var watches = []
switch (watch.type) {
case Watch.types.DELETE:
watches = watches
.concat(this.data[path] || [])
.concat(this.child[path] || [])
.concat(this.exists[path] || [])
delete this.data[path]
delete this.child[path]
delete this.exists[path]
break;
case Watch.types.CHILD:
watches = watches.concat(this.child[path] || [])
delete this.child[path]
break;
default:
watches = watches
.concat(this.data[path] || [])
.concat(this.exists[path] || [])
delete this.data[path]
delete this.exists[path]
break;
}
this.fireWatches(watches, watch)
}
return Watcher
}