rpc-typescript
Version:
An RCP library for TypeScript
48 lines (35 loc) • 1.07 kB
text/typescript
import { ContractReference } from "../types";
import { IEndpointContext } from "./IEndpointContext";
export class ContextDomain<TCtx extends IEndpointContext> {
private _ctx: Record<string, TCtx>;
private _factory: (name: string) => TCtx;
constructor(factory: (name: string) => TCtx) {
this._ctx = {};
this._factory = factory;
}
public getContext(
name?: string
): TCtx {
if (typeof name === 'undefined') {
name = 'default';
}
let instance = this._ctx[name];
if (typeof instance === 'undefined') {
instance = this._factory(name);
this._ctx[name] = instance;
}
return instance;
}
public getChannel<T>(
contract: ContractReference<T>,
contextName?: string
): T {
const ctx = this.getContext(contextName);
return ctx.createChannel(contract);
}
public clear(
name: string
): void {
delete this._ctx[name];
}
}