Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CQRS: Type-safe class decorator #16

Open
tjbroodryk opened this issue Jan 2, 2023 · 0 comments
Open

CQRS: Type-safe class decorator #16

tjbroodryk opened this issue Jan 2, 2023 · 0 comments

Comments

@tjbroodryk
Copy link

Hey there, first of all i'd like to say excellent work on the projects in this repo, the typed cqrs package is awesome!

Is your feature request related to a problem? Please describe.
I've ran into a minor DX issue a few times where i update the class annotation to handle a different command e.g. @CommandHandler(Command1) -> @Commandhandler(OtherCommand).
Because the type-safety of the handler class is currently enforced by the IInferredCommandHandler interface, i'd need to remember to update the implements clause as well.

Describe the solution you'd like
It would be nice if the type-safety for the handler came from the decorator, allowing us to omit the need for the interface, and only needing to reference the target command in one place.

Could maybe be achieved like so:

import { CommandHandler as BaseCommandHandler } from "@nestjs-architects/typed-cqrs"

type InferredResultType<CommandType extends Command<unknown>> = CommandType extends Command<infer R> ? R
: never;

interface Handler<T extends Command<unknown>> {
  execute(command: T): Promise<InferredResultType<T>>
}

export const CommandHandler = <C extends Command<unknown>>(command: Constructor<C>) => {
  return (target: Constructor<Handler<C>>) => {
    BaseCommandHandler(command)(target)
  };
};

Allowing the handler to look like so:

@CommandHandler(SomeCommand)
export class MyHandler {
  async execute(command: SomeCommand) {
    //stuff
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant