vendredi 9 septembre 2022

Typescript, create a Mediator resolver for classes

I'm new with Typescript and I'm trying to create something like MediatR for C# in Typescript.

I've this scenario:

Interfaces:

export interface ICommand {}

export interface ICommandResult {}

export interface ICommandHandler<ICommand, ICommandResult> {
    execute(request: ICommand): ICommandResult;
}

implementations:

export interface ConcreteCommand extends ICommand {
    name: string;
}

export interface ConcreteResult extends ICommandResult {
    name: string;
}

export class ConcreteCommandHandler
    implements ICommandHandler<ConcreteCommand, ConcreteResult> {
    public execute(request: ConcreteCommand): ConcreteResult {
        let result: ConcreteResult = {
            name: request.name
        }

        return result;
    }
}

What I want to reach is something like this:

//pseudocode!
let command: ConcreteCommand = { 
 name: "mycommand!";
}

let handler = CommandHandlersFactory().Create<ConcreteCommand>(command);
let result = handler.execute();

But I'm stuck inside the "CommandHandlersFactory().Create()" implementation because I don't know to to resolve the right CommandHandler with the right key (type).

My idea was to have a Map<ICommand, ICommandHandler>() so I can do something like this:

//Psudocode!
_map<ICommand, ICommandHandler>() = new Map();
_map.set(ConcreteCommand, ConcreteCommandHandler);
 
Create<T>(command: ICommand) {
 let concreteCommandHandlerType = _map[command];
 return new concreteCommandHandlerType();
}

Is even possibile to do something like this in Typescript?

Thanks a lot!





Aucun commentaire:

Enregistrer un commentaire