import { TRPCError } from '@trpc/server'; type ClassName = any; export class InstanceManager { private instanceMap: Map>; constructor() { this.instanceMap = new Map(); } /** * Clear instances by socket id. * @param socketId The socket id of each connection. */ clearAllInstances(socketId: number) { this.instanceMap.get(socketId)?.clear(); this.instanceMap.delete(socketId); } /** * Clear instance by socket id and instanceId. * @param socketId The socket id of each connection. * @param instanceId The instance id to be cleared. */ clearInstance(socketId: number, instanceId: string) { this.instanceMap.get(socketId)?.delete(instanceId); } /** * Set instance by socket id and instance id. * @param socketId The socket id of each connection. * @param instanceId The id of instance. * @param intance Instance. */ setInstance(socketId: number, instanceId: string, intance: ClassName) { if (!this.instanceMap.has(socketId)) { this.instanceMap.set(socketId, new Map()); } this.instanceMap.get(socketId)!.set(instanceId, intance); } /** * Get instance by socket id and instance id. * @param socketId The socket id of each connection. * @param instanceId The id of instance. * @returns Instance. */ getInstance(socketId: number, instanceId: string): ClassName { const map = this.instanceMap.get(socketId); if (map && map.get(instanceId)) { return map.get(instanceId)!; } else { throw new TRPCError({ code: 'BAD_REQUEST', message: `The instance of instanceId(${instanceId}) of socketId(${socketId}) does not exist, please call 'createInstance' first.` }); } } }