The parameter of type 'Class' cannot be assigned to the parameter of type 'AggregateRoot<IEvent>'

Having trouble with my CommandHandler. Encountering an error that's proving tricky to resolve. Any insights on what might be causing this issue?

Error message: Argument of type 'User' is not assignable to parameter of type 'AggregateRoot'. Type 'User' is missing the following properties from type 'AggregateRoot': [IS_AUTO_COMMIT_ENABLED], [INTERNAL_EVENTS]ts(2345)

// user.repository.ts
...

@Injectable()
export class UserRepository extends Repository<User> {
    constructor(private dataSource: DataSource) {
        super(User, dataSource.createEntityManager());
    }

    async createUser(userRegisterDto: UserRegisterDto) {
        const id = uuidv4();
        const user = await this.save(
            super.create({ ...{ id }, ...userRegisterDto }),
        );
        user.create();
        return user;
    }

    async updateUser(userDto: UserDto) {
        const updatedUser = await super.findOne({
            where: { id: userDto.id },
        });

        updatedUser.update();

        return updatedUser;
    }

    async deleteUser(userDto: UserDto) {
        const deletedUser = await super.findOne({
            where: { id: userDto.id },
        });

        deletedUser.delete();

        return await super.delete(userDto.id);
    }
}

// create-user.handler.ts
...

@CommandHandler(CreateUserCommand)
export class CreateUserHandler implements ICommandHandler<CreateUserCommand> {
    constructor(
        private readonly _repository: UserRepository,
        private readonly _publisher: EventPublisher,
    ) {}

    async execute(command: CreateUserCommand): Promise<void> {
        Logger.log('Async CreateUserHandler...', 'CreateUserCommand');

        await this._repository
            .findOne({ where: { email: command.userRegisterDto.email } })
            .then((user) => {
                if (user) {
                    throw new HttpException(
                        'User with this email already exists',
                        HttpStatus.CONFLICT,
                    );
                }
            });

        const { userRegisterDto } = command;
        const user = this._publisher.mergeObjectContext(
            await this._repository.createUser(userRegisterDto),
        );

        user.commit();
    }
}

The User class extends an AbstractEntity which extends AggregateRoot:

// abstract.entity.ts
'use strict';
import { AggregateRoot } from '@nestjs/cqrs';
import { IAggregateEvent } from 'nestjs-eventstore';
import {
    CreateDateColumn,
    PrimaryGeneratedColumn,
    UpdateDateColumn,
} from 'typeorm';

export abstract class AbstractEntity extends AggregateRoot<IAggregateEvent> {
    @PrimaryGeneratedColumn('uuid')
    id!: string;

    @CreateDateColumn({ type: 'timestamp', name: 'created_at' })
    createdAt: Date;

    @UpdateDateColumn({ type: 'timestamp', name: 'updated_at' })
    updatedAt: Date;

    abstract toDto();
}

Answer №1

It appears that your User model does not extend the AggregateRoot class. Please refer to the documentation for an example:

export class Hero extends AggregateRoot {
  constructor(private id: string) {
    super();
  }

Two important values (IS_AUTO_COMMIT_ENABLED and INTERNAL_EVENTS) are part of the AggregateRoot class. You can find them in the implementation. Make sure your extension includes these values.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Configuring TypeORM to connect to multiple databases

For my backend project, I am utilizing node.js, TS, and typeorm as my tools. I have a requirement to establish a connection to a different database within the middleware based on the parameter I send, and then execute queries against that database. Here ...

Access the Angular application directly from the email

Our infrastructure consists of a .NET back-end, an Angular 5 application, and a nginx server. Upon registering your account in the application, you will receive an email with a verification link structured as follows: [root]/register/verify?userId=blabla& ...

Unable to handle errors when making API requests

I'm currently working on a custom hook and I need to handle errors that may occur during an API call to adjust the display. Here's the code for the custom hook: function useBook() { const [book, setBook] = useState<Book | any>() con ...

TSLint now requires promises to be handled correctly using the `finally` clause

Encountering an error from TSLint, I am working to comprehend why it is raising concerns. In my code, there is a function that calls another method which returns a promise. However, the initial function does not return the promise; instead, it waits for c ...

Navigating through a large array list that contains both arrays and objects in Typescript:

I have an array containing arrays of objects, each with at least 10 properties. My goal is to extract and store only the ids of these objects in the same order. Here is the code I have written for this task: Here is the structure of my data: organisationC ...

Is the stepper's vertical line separating when the label extends onto multiple lines?

I'm facing an issue with the text inside my MaterialUI Stepper // StepLabel, where it sometimes wraps over multiple lines. Is there a way to keep the vertical StepConnectors attached to the StepIcons regardless of the number of lines of text in the l ...

Converting JSON to TypeScript: How to properly serialize property names instead of the base class field names

Take a look at the code snippet below. I anticipate the serialized result to be: { "origin": { "x": 1, "y": 2 }, "size": { "width": 3, "height": 4 } } However, the actual result is: { "origin": { ...

Encountering HttpErrorResponse when sending a Delete request in Angular

I need help troubleshooting an issue with sending a Delete request from my movie.component.ts file to delete a review. Unfortunately, I keep receiving the dreaded HttpErrorResponse error. Can anyone pinpoint where I may be making a mistake? Take a look at ...

Modifying the component's property value with an observable in Angular 2

In my project, I have implemented two components that share a service. The first component contains 2 buttons which trigger the methods squeezeContent() and unsqueezeContent() on click. These methods pass a numeric value to an observable in the shared serv ...

Having trouble sending correct true/false values for selected radio buttons on an Angular5 table, often requiring users to click them twice to submit the appropriate values

My goal is to assign true or false values to selected radio buttons in each row and then form an object for submission. To distinguish between the radio button values in each row, I have used {{k}}+{{sizeobj.rbSelected}} as the value which is causing issue ...

Sending data back to a previous screen in React Native

Currently, I am facing an issue with passing parameters between two screens: HomeScreen and SavedRoutesScreen. function HomeScreen(props: { //some props route:any, navigation:any, }) { React.useEffect(() => { if (props.route.params?.defin ...

Approach for retrieving users by utilizing forEach loop in Mongoose

I have a list of profile IDs that looks like get profiles [ '62d80ece61a85d738fa0c297', '62d80fb061a85d738fa0c29c' ] I am trying to iterate through this list and use each ID in the find() method Here is my code snippet: let total ...

The properties of cloned objects in ThreeJS are unable to be defined

While working in ThreeJS using TypeScript, I encountered an issue when attempting to clone a custom object that extends Object3D. The problem arises when the field, which is required for creating a new object, becomes undefined during the cloning process. ...

Guide on importing JavaScript into TypeScript without using noImplicityAny and while not allowing Js

In my development setup, I am utilizing Webpack along with @babel/typescript to compile a project that consists of a mix of TypeScript and JavaScript. To ensure better typing and take advantage of the benefits it offers, I have enabled the --noImplicitAny ...

Creating, editing, and deleting data in Ng2 smart table is a seamless process that can greatly enhance

While working on my Angular 2 project, I utilized [ng2 smart table]. My goal was to send an API request using the http.post() method. However, upon clicking the button to confirm the data, I encountered the following error in the console: ERROR TypeErro ...

The issue arises in React when input elements fail to render correctly following a change in value, specifically when the keys remain identical

Click here to view the code sandbox showcasing the issue The code sandbox demonstrates two versions - a working one where Math.random() is used as the key, and a not working one where the index of the array is used as the key. When the array this.state.v ...

Browse through TypeScript objects using a browser tool

In my current workflow with VS 2015, I rely on the "Object browser" window for C# to easily navigate types in assemblies and namespaces, method overloads, and more. Is there a similar tool available for TypeScript that can browse TypeScript definition fil ...

What is the best way to prevent double clicks when using an external onClick function and an internal Link simultaneously

Encountering an issue with nextjs 13, let me explain the situation: Within a card component, there is an external div containing an internal link to navigate to a single product page. Using onClick on the external div enables it to gain focus (necessary f ...

Implementing Vite with Typescript for React 17

Are there instructions for setting up Vite and Typescript with React 17 instead of 18? Currently, our team is working on React version 17.0.2 and contemplating the adoption of Typescript. ...

Sharing items while navigating through the router

Is there a better way to pass objects when navigating to a target component using Angular router? Currently, I am using routeParams and stringifying my objects, but I'm not satisfied with this approach. What would an improved solution entail? export ...