nestjs / cqrs

A lightweight CQRS module for Nest framework (node.js) :balloon:
https://nestjs.com
MIT License
832 stars 149 forks source link

Support for Request Scoped/Durable Providers #1685

Open petrusdemelo opened 5 months ago

petrusdemelo commented 5 months ago

Is there an existing issue that is already proposing this?

Is your feature request related to a problem? Please describe it

Currently the nestjs/cqrs doesn't support request scoped dependencies into the handlers. Thus, if a @CommandHandler provider depends on another provider marked as Request Scoped, this provider comes as undefined. That also impacts multi-tenancy applications.

Describe the solution you'd like

pseudocode

public async execute<TCommand extends ICommand, TResult extends IResult>(command: TCommand): Promise<TResult> {
    const commandName = command.constructor.name;
    let handler = this.commandRegister.getHandlerSingleton(commandName);

    if (!handler) {
        const handlerType = this.commandRegister.getHandlerType(commandName);
        const contextId = ContextIdFactory.getByRequest(this.request);
        if (handlerType) {
            this.moduleRef.registerRequestByContextId(
                { ... this.context },
                contextId,
            );
            handler = await this.moduleRef.resolve(handlerType, contextId, { strict: false });
        }
    }

    if (!handler) {
        throw new Error(`Command handler not found for ${commandName}`);
    }

    return handler.execute(command);
}

I know there is the commandId instead of commandName to identify the commands. This is just an a example.

Teachability, documentation, adoption, migration strategy

Send a pull request that handles with the instantiation of the handlers request scoped and respect the strategy applied ContextIdFactory

What is the motivation / use case for changing the behavior?

Use nestjs/cqrs in a multi tenancy application.

petrusdemelo commented 5 months ago

I spent the weekend looking into the discussions and proposed implementations below as well as reading the nestjs/cqrs codebase.

https://github.com/nestjs/cqrs/issues/60 https://github.com/nestjs/cqrs/pull/549

And I'm able to create and send a pull request to contribute to this. However, the last PR hung for three years without merging. I'd like to understand if it's worthwhile to move on with the contribution or if it's something that I should wait for other contributors.

I wouldn't want to open a PR and close after three years as the last person did.

I implemented my own version of the feature and I'm using it currently in the place of nestjs/cqrs. But I want to become a contributor so I imagine this is a good opportunity.

I created this new issue because I'm not able to answer the mentioned one.