import Service, { type ServiceApi, type ServiceConfig } from "./Service"; import type { HandlerStatsReport, Stats } from "./ServiceStats"; export interface DefaultClient { ping(): Promise; /** * Retrieve stats for the service, and any clients that it uses. * Note: if there are multiple instances of the service (load balanced), * then the stats will be for a random instance. */ getStats(): Promise; stats: Record; isConnected: boolean; } export interface StandaloneClient extends DefaultClient { connect(): Promise; disconnect(): Promise; } export type ClientConfig, D extends string = T["domain"]> = Omit< ServiceConfig, "handlers" >; const clientCache = new Map(); const ServiceClient = { /** * Create a client for the given service domain. * * @param domain * @param config * @returns */ create, D extends string = T["domain"]>( domain: D, config?: ClientConfig, ): T["handlers"] & StandaloneClient { return new Service(domain, config).getClient() as T["handlers"] & StandaloneClient; }, /** * Get a cached client for the given service domain. Create it if it doesn't exist. * * @param domain * @param config * @returns */ get, D extends string = T["domain"]>( domain: D, config?: ClientConfig, ): T["handlers"] & StandaloneClient { const key = `${domain}:${JSON.stringify(config)}`; if (!clientCache.has(key)) { clientCache.set( key, new Service(domain, config).getClient() as T["handlers"] & StandaloneClient, ); } return clientCache.get(key) as T["handlers"] & StandaloneClient; }, }; export default ServiceClient;