Refactor CaslService OrganizationGroupMembersRoleChanged

Refactor the method like this:

// CaslService

// OrganizationGroupMembersRoleChanged
async handleGroupMembersRoleChanged(
    payload: GroupMembersRoleChangedDto,
  ): Promise<void> {
    await this.deleteGroupMembersSecondaryRoles(
      payload.organizationId,
      payload.groupMembers.map((member) => member.profile.id),
      payload.secondaryRole,
    );

    const dtos = UpsertPrivilegeDto.fromOrganizationGroup(payload);

    // TODO replace it with bulkWrite
    await Promise.all(dtos.map(async (dto) => this.upsertPrivilege(dto)));
  }

  // deleteOrganizationSecondaryRole
  private async deleteGroupMembersSecondaryRoles(
    organizationId: string,
    userIds: string[],
    secondaryRoles: OrganizationSecondaryRole[],
  ): Promise<void> {
    const rolesToDelete =
      secondaryRoles.length === 0
        ? Object.values(OrganizationSecondaryRole)
        : Object.values(OrganizationSecondaryRole).filter(
            (role) => !secondaryRoles.includes(role),
          );

    const roleIds =
      await this.rolesService.retrieveRoleIdsByLookupKeys(rolesToDelete);

    await this.privilegesRepository.deleteMany({
      userId: { $in: userIds },
      resourceId: organizationId,
      roleId: { $in: roleIds },
    });
  }

// RolesService

async retrieveRoleIdsByLookupKeys(lookupKeys: string[]): Promise<string[]> {
    const roles = await this.repository.find({
      lookupKey: { $in: lookupKeys },
    });

    return roles.map((role) => role.id);
  }

Note: replace Promise.all + map with bulkWrite operation

Domain
AuthN-Z
Action
refactor
Department
Backend

Please authenticate to join the conversation.

Upvoters
Status

Completed

Board
๐Ÿ› ๏ธ

Bug & Fixes

Tags

Low Priority

Date

11 months ago

Author

Ivan Ligotino

Subscribe to post

Get notified by email when there are changes.