|
| 1 | +import type { PostgresConnection } from 'pg-gateway' |
| 2 | +import type { WebSocket } from 'ws' |
| 3 | + |
| 4 | +type DatabaseId = string |
| 5 | +type ConnectionId = string |
| 6 | + |
| 7 | +class ConnectionManager { |
| 8 | + private socketsByDatabase: Map<DatabaseId, ConnectionId> = new Map() |
| 9 | + private sockets: Map<ConnectionId, PostgresConnection> = new Map() |
| 10 | + private websockets: Map<DatabaseId, WebSocket> = new Map() |
| 11 | + |
| 12 | + constructor() {} |
| 13 | + |
| 14 | + public hasSocketForDatabase(databaseId: DatabaseId) { |
| 15 | + return this.socketsByDatabase.has(databaseId) |
| 16 | + } |
| 17 | + |
| 18 | + public getSocket(connectionId: ConnectionId) { |
| 19 | + return this.sockets.get(connectionId) |
| 20 | + } |
| 21 | + |
| 22 | + public getSocketForDatabase(databaseId: DatabaseId) { |
| 23 | + const connectionId = this.socketsByDatabase.get(databaseId) |
| 24 | + return connectionId ? this.sockets.get(connectionId) : undefined |
| 25 | + } |
| 26 | + |
| 27 | + public setSocket(databaseId: DatabaseId, connectionId: ConnectionId, socket: PostgresConnection) { |
| 28 | + this.sockets.set(connectionId, socket) |
| 29 | + this.socketsByDatabase.set(databaseId, connectionId) |
| 30 | + } |
| 31 | + |
| 32 | + public deleteSocketForDatabase(databaseId: DatabaseId) { |
| 33 | + const connectionId = this.socketsByDatabase.get(databaseId) |
| 34 | + this.socketsByDatabase.delete(databaseId) |
| 35 | + if (connectionId) { |
| 36 | + this.sockets.delete(connectionId) |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + public hasWebsocket(databaseId: DatabaseId) { |
| 41 | + return this.websockets.has(databaseId) |
| 42 | + } |
| 43 | + |
| 44 | + public getWebsocket(databaseId: DatabaseId) { |
| 45 | + return this.websockets.get(databaseId) |
| 46 | + } |
| 47 | + |
| 48 | + public setWebsocket(databaseId: DatabaseId, websocket: WebSocket) { |
| 49 | + this.websockets.set(databaseId, websocket) |
| 50 | + } |
| 51 | + |
| 52 | + public deleteWebsocket(databaseId: DatabaseId) { |
| 53 | + this.websockets.delete(databaseId) |
| 54 | + this.deleteSocketForDatabase(databaseId) |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +export const connectionManager = new ConnectionManager() |
0 commit comments