36 lines
889 B
TypeScript
36 lines
889 B
TypeScript
|
|
let singleton: UserChannel = null;
|
|
|
|
export default class UserChannel {
|
|
private subscription;
|
|
private constructor(private ws) {
|
|
this.subscription = null;
|
|
}
|
|
|
|
async connect(): Promise<boolean> {
|
|
this.subscription = this.ws.subscribe(`user_channel`);
|
|
const subscription = this.subscription;
|
|
const self = this;
|
|
return new Promise((resolve, reject) => {
|
|
subscription.on('error', () => { resolve(false) });
|
|
subscription.on('ready', () => {
|
|
resolve(true)
|
|
});
|
|
subscription.on('close', self.close);
|
|
});
|
|
}
|
|
|
|
on(event: string, callback: (...args) => void) {
|
|
if (this.subscription) this.subscription.on(event, callback);
|
|
}
|
|
|
|
static async getInstance(ws) {
|
|
if (singleton) return singleton;
|
|
singleton = new UserChannel(ws);
|
|
return singleton;
|
|
}
|
|
close() {
|
|
this.subscription.close();
|
|
singleton = null;
|
|
}
|
|
}
|