From 8750da7e6211100e42404c74f4552505a975d232 Mon Sep 17 00:00:00 2001 From: faris Aljohari <83524184+farisaljohari@users.noreply.github.com> Date: Thu, 15 May 2025 10:09:29 +0300 Subject: [PATCH] feat: optimize getAllDevicesByCommunity to prevent duplicate space processing --- src/device/services/device.service.ts | 31 +++++++++++---------------- 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/src/device/services/device.service.ts b/src/device/services/device.service.ts index 717affd..4d4efbb 100644 --- a/src/device/services/device.service.ts +++ b/src/device/services/device.service.ts @@ -1812,7 +1812,6 @@ export class DeviceService { async getAllDevicesByCommunity( communityUuid: string, ): Promise { - // Fetch the community and its top-level spaces const community = await this.communityRepository.findOne({ where: { uuid: communityUuid }, relations: [ @@ -1828,37 +1827,33 @@ export class DeviceService { } 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;