From e253d1ca03c49312e098fac2f651863e64e6da0d Mon Sep 17 00:00:00 2001 From: faris Aljohari <83524184+farisaljohari@users.noreply.github.com> Date: Thu, 15 May 2025 10:08:02 +0300 Subject: [PATCH] refactor: optimize device retrieval by avoiding duplicate space visits in getAllDevicesByCommunity --- src/community/services/community.service.ts | 31 +++++++++------------ 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/src/community/services/community.service.ts b/src/community/services/community.service.ts index cb166e7..542926c 100644 --- a/src/community/services/community.service.ts +++ b/src/community/services/community.service.ts @@ -313,7 +313,6 @@ export class CommunityService { async getAllDevicesByCommunity( communityUuid: string, ): Promise { - // Fetch the community and its top-level spaces const community = await this.communityRepository.findOne({ where: { uuid: communityUuid }, relations: [ @@ -329,37 +328,33 @@ export class CommunityService { } const allDevices: DeviceEntity[] = []; + const visitedSpaceUuids = new Set(); - // Recursive fetch function for spaces + // Recursive fetch function with visited check const fetchSpaceDevices = async (space: SpaceEntity) => { - if (space.devices && space.devices.length > 0) { + if (visitedSpaceUuids.has(space.uuid)) return; + visitedSpaceUuids.add(space.uuid); + + if (space.devices?.length) { allDevices.push(...space.devices); } - if (space.children && space.children.length > 0) { - for (const childSpace of space.children) { - const fullChildSpace = await this.spaceRepository.findOne({ - where: { uuid: childSpace.uuid }, + if (space.children?.length) { + for (const child of space.children) { + const fullChild = await this.spaceRepository.findOne({ + where: { uuid: child.uuid }, relations: ['children', 'devices', 'devices.productDevice'], }); - if (fullChildSpace) { - await fetchSpaceDevices(fullChildSpace); + if (fullChild) { + await fetchSpaceDevices(fullChild); } } } }; - // Start recursive fetch for all top-level spaces for (const space of community.spaces) { - const fullSpace = await this.spaceRepository.findOne({ - where: { uuid: space.uuid }, - relations: ['children', 'devices', 'devices.productDevice'], - }); - - if (fullSpace) { - await fetchSpaceDevices(fullSpace); - } + await fetchSpaceDevices(space); } return allDevices;