-
Notifications
You must be signed in to change notification settings - Fork 568
/
watcher.ts
64 lines (57 loc) 路 1.45 KB
/
watcher.ts
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
import { Watcher } from 'casbin';
import Redis from 'ioredis';
export abstract class BaseWatcher<Client> implements Watcher {
private callback: () => void;
constructor(
protected options: {
subClient: Client;
pubClient?: Client;
subscribeKeyName?: string;
}
) {
this.options.subscribeKeyName =
this.options.subscribeKeyName || this.getDefaultSubscribeKeyName();
if (!this.options.pubClient) {
this.options.pubClient = this.options.subClient;
}
this.subscribeData(() => {
if (this.callback) {
this.callback();
}
});
}
setUpdateCallback(callback: () => void) {
this.callback = callback;
}
async update(): Promise<boolean> {
try {
await this.publishData();
return true;
} catch (err) {
return false;
}
}
abstract publishData();
abstract subscribeData(callback);
protected async close() {}
getDefaultSubscribeKeyName(): string {
return 'casbin-data-sync';
}
}
export class NodeRedisWatcher extends BaseWatcher<Redis> {
async publishData() {
await this.options.pubClient.publish(
this.options.subscribeKeyName,
'casbin rules updated'
);
}
async subscribeData(callback) {
await this.options.subClient.subscribe(this.options.subscribeKeyName);
this.options.subClient.on('message', channel => {
if (channel !== this.options.subscribeKeyName) {
return;
}
callback();
});
}
}