diff --git a/src/community/services/community.service.ts b/src/community/services/community.service.ts index 96484c2..54516fb 100644 --- a/src/community/services/community.service.ts +++ b/src/community/services/community.service.ts @@ -25,7 +25,7 @@ import { NotFoundException, } from '@nestjs/common'; import { SpaceService } from 'src/space/services'; -import { QueryRunner, SelectQueryBuilder } from 'typeorm'; +import { Brackets, QueryRunner, SelectQueryBuilder } from 'typeorm'; import { AddCommunityDto, GetCommunityParams, ProjectParam } from '../dtos'; import { UpdateCommunityNameDto } from '../dtos/update.community.dto'; @@ -184,18 +184,46 @@ export class CommunityService { let qb: undefined | SelectQueryBuilder = undefined; + const matchingCommunityIdsQb = this.communityRepository + .createQueryBuilder('c') + .select('c.uuid') + .where('c.project = :projectUuid', { projectUuid }) + .andWhere('c.name != :orphanCommunityName', { + orphanCommunityName: `${ORPHAN_COMMUNITY_NAME}-${project.name}`, + }) + .distinct(true); + if (includeSpaces) { + matchingCommunityIdsQb.leftJoin('c.spaces', 'space'); + } + + if (search) { + matchingCommunityIdsQb + .andWhere( + new Brackets((qb) => { + qb.where('c.name ILIKE :search'); + if (includeSpaces) qb.orWhere('space.spaceName ILIKE :search'); + }), + ) + .setParameter('search', `%${search}%`); + } + qb = this.communityRepository .createQueryBuilder('c') .where('c.project = :projectUuid', { projectUuid }) - .andWhere(`c.name != '${ORPHAN_COMMUNITY_NAME}-${project.name}'`) - .distinct(true); - + .andWhere('c.name != :orphanCommunityName', { + orphanCommunityName: `${ORPHAN_COMMUNITY_NAME}-${project.name}`, + }) + .andWhere(`c.uuid IN (${matchingCommunityIdsQb.getQuery()})`) + .setParameters(matchingCommunityIdsQb.getParameters()); if (includeSpaces) { qb.leftJoinAndSelect( 'c.spaces', 'space', 'space.disabled = :disabled AND space.spaceName != :orphanSpaceName', - { disabled: false, orphanSpaceName: ORPHAN_SPACE_NAME }, + { + disabled: false, + orphanSpaceName: ORPHAN_SPACE_NAME, + }, ) .leftJoinAndSelect('space.parent', 'parent') .leftJoinAndSelect( @@ -204,16 +232,7 @@ export class CommunityService { 'children.disabled = :disabled', { disabled: false }, ); - // .leftJoinAndSelect('space.spaceModel', 'spaceModel') } - - if (search) { - qb.andWhere( - `c.name ILIKE :search ${includeSpaces ? 'OR space.space_name ILIKE :search' : ''}`, - { search: `%${search}%` }, - ); - } - const customModel = TypeORMCustomModel(this.communityRepository); const { baseResponseDto, paginationResponseDto } =