-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis.ts
41 lines (35 loc) · 1.08 KB
/
redis.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
import RedisClient from 'ioredis';
import Io from './io';
import { RedisOptions } from './types';
export class Redis extends RedisClient {
public options: RedisOptions;
public constructor(io: Io) {
io.config.defaults({
redis: {
host: 'localhost',
port: 6379,
db: 0,
},
});
super(io.config.get('redis'));
this.options = io.config.get<RedisOptions>('redis');
}
/**
* Subscribe to changes on a key.
* @param {string} key - The key.
* @param {function} handler - Callback function to handle the change event
* @returns {any} - The subscriber. Use subsriber.unsubscribe((err, result)=>{}) to unsubscribe.
*/
public onChange(key: string, handler: (event: unknown) => void): RedisClient.Redis {
const keyChannel = `__keyspace@${this.options.db}__:${key}`;
const subscriber = this.duplicate();
subscriber.subscribe(keyChannel);
subscriber.on('message', (channel, event): void => {
if (channel === keyChannel) {
handler(event);
}
});
return subscriber;
}
}
export default Redis;