Assign role route

A route for the admin to assign roles to other users.

Now, we'll create a route so that the admin can assign roles with higher privileges to other users. Let's then begin by creating the file auth -> roles -> dto -> role.dto. We use the @IsEnum() decorator to check if the field corresponds to a value of an enum.

export class RoleDto {
  @IsEnum(Role)
  readonly role: Role;
}

Then, we shall return to the AuthController and create the route assignRole().

@Patch(':id/assign-role')
assignRole(@Param() { id }: IdDto, @Body() { role }: RoleDto) {
  return this.authService.assignRole(id, role);
}

And in the AuthService, create the namesake method with the logic for assigning a role.

async assignRole(id: number, role: Role) {
  const user = await this.usersRepository.preload({
    id,
    role,
  });
  if (!user) {
    throw new NotFoundException('User not found');
  }
  return this.usersRepository.save(user);
}

Commit - Creating assign role route and validating enum in dto

Last updated