Problem with findOne verification

Asked

Viewed 43 times

1

I am using typeorm and postgres. In my use case I have a execute method:

  async execute({ name, email, password }: ICreateUserDTO): Promise<void> {
    const userExists = await this.usersRepository.findByEmail(email);

    if (userExists) {
      throw new Error(`User ${name} already exists`);
    }

    this.usersRepository.create({ name, email, password });
  }
}

In my repository:

  async findByEmail(email: string): Promise<User> {
    const user = await this.repository.findOne({ email });
    return user;
  }

I can create a user normally, but if the email already exists it won’t let me create any more users, even with different email. Always returning the same error

Error: User admin already exists
app             |     at CreateUserUseCase.<anonymous> (/usr/app/src/modules/users/useCases/createUser/CreateUserUseCase.ts:13:13)
app             |     at step (/usr/app/src/modules/users/useCases/createUser/CreateUserUseCase.ts:33:23)
app             |     at Object.next (/usr/app/src/modules/users/useCases/createUser/CreateUserUseCase.ts:14:53)
app             |     at fulfilled (/usr/app/src/modules/users/useCases/createUser/CreateUserUseCase.ts:5:58)
app             |     at processTicksAndRejections (node:internal/process/task_queues:96:5)
app             | [ERROR] 22:48:59 Error: User admin already exists
  • 1

    What this.repository.findOne returns in this case? What I understood is that because of this Promise<User> it returns some object, even if the email doesn’t exist. I don’t know if it should be something like Promise<User | null>, for case email does not exist, it returns null,. but it’s just a hunch.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.