nestjs-packages
nestjs-packages copied to clipboard
CQRS: Type-safe class decorator
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
}
}