forked from persvr/perstore
/
notifying.js
90 lines (89 loc) · 2.27 KB
/
notifying.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
/**
* This should wrap data stores that connect to a central repository, in order
* to distribute data change notifications to all store subscribers.
*/
var getChildHub = require("tunguska/hub").getChildHub,
when = require("promised-io/promise").when;
exports.Notifying = function(store, options){
if(store.subscribe){
// already notifying
return store;
}
var hub;
var localHub;
var originalSetPath = store.setPath;
store.setPath = function(id){
hub = getChildHub(id);
localHub = hub.fromClient("local-store");
if(originalSetPath){
originalSetPath(id);
}
};
store.subscribe = function(path, directives){
var clientHub = hub;
if(directives && directives['client-id']){
clientHub = hub.fromClient(directives['client-id']);
}
return clientHub.subscribe(path, /*directives.body || */["put", "delete"]);
};
store.unsubscribe = function(path, directives){
var clientHub = hub;
if(directives && directives['client-id']){
clientHub = hub.fromClient(directives['client-id']);
}
return clientHub.unsubscribe(path, ["put", "delete"]);
};
var originalPut = store.put;
if(originalPut){
store.put= function(object, directives){
if(options && options.revisionProperty){
object[options.revisionProperty] = (object[options.revisionProperty] || 0) + 1;
}
var result = originalPut(object, directives) || object.id;
if(directives && directives.replicated){
return result;
}
return when(result, function(id){
localHub.publish({
channel: id,
result: object,
type: "put"
});
return id;
});
};
}
var originalAdd = store.add;
if(originalAdd){
store.add= function(object, directives){
var result = originalAdd(object, directives) || object.id;
if(directives && directives.replicated){
return result;
}
return when(result, function(id){
localHub.publish({
channel: id,
result: object,
type: "put"
});
return id;
});
};
}
var originalDelete = store["delete"];
if(originalDelete){
store["delete"] = function(id, directives){
var result = originalDelete(id, directives);
if(directives && directives.replicated){
return result;
}
return when(result, function(){
localHub.publish({
channel: id,
type: "delete"
});
});
};
}
return store;
};