import { Log, logger } from '@spine/logger'; import { Server } from 'http'; export class ListenerManager { name: string; lastConnectionKey: number; connectionMap: any; listener: Server; log: Log; constructor(listener: Server, name?: string, log?: Log) { this.name = name != null ? name : 'listener'; this.lastConnectionKey = 0; this.connectionMap = {}; this.listener = listener; this.log = log != null ? log : logger(this.name); // Track all connections to our server so that we can close them when needed. this.listener.on('connection', (connection) => { // Increment the connection key. this.lastConnectionKey += 1; // Generate a new key to represent the connection const connectionKey = this.lastConnectionKey; // Add the connection to our map. this.connectionMap[connectionKey] = connection; // Remove the connection from our map when it closes. connection.on('close', () => { delete this.connectionMap[connectionKey]; }); }); } killAllConnections() { Object.keys(this.connectionMap).forEach((connectionKey) => { this.connectionMap[connectionKey].destroy(); }); } dispose() { return new Promise((resolve) => { if (this.listener !== undefined) { this.killAllConnections(); this.log( 'info', 'Destroyed all existing connections.', ); this.listener.close(() => { this.log( 'info', 'Closed listener.', ); resolve(); }); } else { resolve(); } }); } }