From 8bc7daa3f344ef4809aa97fae7ac0178034e7e4a Mon Sep 17 00:00:00 2001 From: syuilo Date: Mon, 28 Jun 2021 17:49:25 +0900 Subject: [PATCH] refactor --- src/streaming.ts | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/streaming.ts b/src/streaming.ts index 565cea1b6..70cf0a4f2 100644 --- a/src/streaming.ts +++ b/src/streaming.ts @@ -25,6 +25,7 @@ export default class Stream extends EventEmitter { private sharedConnectionPools: Pool[] = []; private sharedConnections: SharedConnection[] = []; private nonSharedConnections: NonSharedConnection[] = []; + private idCounter = 0; constructor(origin: string, user: { token: string; } | null, options?: { WebSocket?: any; @@ -48,6 +49,11 @@ export default class Stream extends EventEmitter { this.stream.addEventListener('message', this.onMessage); } + @autobind + private genId(): string { + return (++this.idCounter).toString(); + } + @autobind public useChannel(channel: C, params?: Channels[C]['params'], name?: string): Connection { if (params) { @@ -62,7 +68,7 @@ export default class Stream extends EventEmitter { let pool = this.sharedConnectionPools.find(p => p.channel === channel); if (pool == null) { - pool = new Pool(this, channel); + pool = new Pool(this, channel, this.genId()); this.sharedConnectionPools.push(pool); } @@ -83,7 +89,7 @@ export default class Stream extends EventEmitter { @autobind private connectToChannel(channel: C, params: Channels[C]['params']): NonSharedConnection { - const connection = markRaw(new NonSharedConnection(this, channel, params)); + const connection = markRaw(new NonSharedConnection(this, channel, this.genId(), params)); this.nonSharedConnections.push(connection); return connection; } @@ -175,9 +181,8 @@ export default class Stream extends EventEmitter { } } -let idCounter = 0; - // TODO: これらのクラスを Stream クラスの内部クラスにすれば余計なメンバをpublicにしないで済むかも? +// もしくは @internal を使う? https://www.typescriptlang.org/tsconfig#stripInternal class Pool { public channel: string; public id: string; @@ -186,11 +191,10 @@ class Pool { private disposeTimerId: any; private isConnected = false; - constructor(stream: Stream, channel: string) { + constructor(stream: Stream, channel: string, id: string) { this.channel = channel; this.stream = stream; - - this.id = (++idCounter).toString(); + this.id = id; this.stream.on('_disconnected_', this.onStreamDisconnected); } @@ -312,11 +316,11 @@ class NonSharedConnection extend public id: string; protected params: Channel['params']; - constructor(stream: Stream, channel: string, params: Channel['params']) { + constructor(stream: Stream, channel: string, id: string, params: Channel['params']) { super(stream, channel); this.params = params; - this.id = (++idCounter).toString(); + this.id = id; this.connect(); }