m4ss1m0g / mediatr-ts

Mediator patter for Typescript, inspired to MediatR csharp library
MIT License
50 stars 10 forks source link

Resolver try to find handler under name of the event ( using di container ) #22

Closed parav01d closed 1 year ago

parav01d commented 1 year ago

I use your library together with a dependency injection container. I noticed that I have to store my handler under the name of my event in the container as a string, otherwise it will not be found. The behavior is also understandable under src/models/mediator.ts. There the send method searches for the handler under the name of the event.

Shouldn't the decorator @requestHandler(Request) set the name of the handler for the request?

public async send(request: IRequest): Promise { const name = request.constructor.name; const handler = mediatorSettings.resolver.resolve<IRequestHandler<IRequest, T>>(name); ... }

m4ss1m0g commented 1 year ago

I do not know what DI container you use. Maybe I don't understand correctly your question, but the send method searches the name because it stores the handler with the name of the function.

const requestHandler = <T>(value: IRequestClass<T>) => {
    return (target: Function): void => {
        const name = (value as Function).prototype.constructor.name;  
        mediatorSettings.resolver.add(name, target); // Here I grab the function name and I pass it with the function itself to thee resolver (container)
    };
};

See the code

Full example

class Request implements IRequest<number> {
        public thenumber: number;

        constructor(thenumber: number) {
            this.thenumber = thenumber;
        }
}

@requestHandler(Request)
class HandlerRequest implements IRequestHandler<Request, string> {

        public handle(value: Request): Promise<string> {
            return Promise.resolve(`We has ${value.thenumber}`);
        }
    }

As you can see the Request string is stored and retrieved from the DI Container. The original MediatR works in the same manner.