chamesu
Version:
This package contains all packages of the chat application.
52 lines (41 loc) • 1.54 kB
text/typescript
/*
* Copyright (c) 2022.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import {RedisClientInterface} from "./index";
class RedisStore {
protected subscriptions : {
[key: string] : CallableFunction[]
}
constructor(protected redisSub: RedisClientInterface, protected redisPub: RedisClientInterface) {
}
public on(channel: string, cb: CallableFunction) : void {
if(!this.subscriptions.hasOwnProperty(channel)) {
this.subscriptions[channel] = [];
}
this.subscriptions[channel].push(cb);
this.redisSub.subscribe(channel).then(() => {
this.redisSub.on('message', this.onMessageEvent);
});
}
protected onMessageEvent(channel: string, data: any) : void {
if(this.subscriptions.hasOwnProperty(channel)) {
const subscriptionsCount : number = this.subscriptions[channel].length;
for(let i=0; i< subscriptionsCount; i++) {
this.subscriptions[channel][i](data);
}
}
}
public async emit(channel: string, data: any) : Promise<boolean> {
return await this.redisPub.publish(channel, data) === 1;
}
}
type RedisStoreContext = {
redisSub: RedisClientInterface,
redisPub: RedisClientInterface
}
export default function createRedisStore({redisSub, redisPub} : RedisStoreContext) {
const redisStore = new RedisStore(redisSub, redisPub);
}