Recover

We should also be able to recover soft-deleted data

Let's return to the UsersController to create a route for recovering a user that was soft-deleted.

@Patch(':id/recover')
recover(@Param() { id }: IdDto) {
  return this.usersService.recover(id);
}

In the UsersService, we shall then create the recover() method too. Here, we'll first find a user in a very similar fashion to the findOne() method, with the sole difference of using the withDeleted option to actually find the soft-deleted record. After that, check if the user exists and if it's actually soft-deleted. Finally, recover it.

async recover(id: number) {
  const user = await this.usersRepository.findOne({
    where: { id },
    relations: {
      orders: {
        items: true,
        payment: true,
      },
    },
    withDeleted: true,
  });

  if (!user) {
    throw new NotFoundException('User not found');
  }
  if (!user.registryDates.deletedAt) {
    throw new ConflictException('User not deleted');
  }

  return this.usersRepository.recover(user);
}

As a minor change, we could go back to the User entity and have a get field to tell if the user has been soft-deleted, by using a double negation operator, like so

get isDeleted() {
  return !!this.registryDates.deletedAt;
}

And then use it when checking if the user has been soft-deleted. With this, we now have soft delete functionality in our system.

Commit - Applying soft delete

Last updated