mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-17 03:05:13 +00:00
Merge pull request #374 from SyncrowIOT/fix-duplication-devices-by-community
refactor: optimize device retrieval by avoiding duplicate space visits in getAllDevicesByCommunity
This commit is contained in:
@ -313,7 +313,6 @@ export class CommunityService {
|
|||||||
async getAllDevicesByCommunity(
|
async getAllDevicesByCommunity(
|
||||||
communityUuid: string,
|
communityUuid: string,
|
||||||
): Promise<DeviceEntity[]> {
|
): Promise<DeviceEntity[]> {
|
||||||
// Fetch the community and its top-level spaces
|
|
||||||
const community = await this.communityRepository.findOne({
|
const community = await this.communityRepository.findOne({
|
||||||
where: { uuid: communityUuid },
|
where: { uuid: communityUuid },
|
||||||
relations: [
|
relations: [
|
||||||
@ -329,37 +328,33 @@ export class CommunityService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const allDevices: DeviceEntity[] = [];
|
const allDevices: DeviceEntity[] = [];
|
||||||
|
const visitedSpaceUuids = new Set<string>();
|
||||||
|
|
||||||
// Recursive fetch function for spaces
|
// Recursive fetch function with visited check
|
||||||
const fetchSpaceDevices = async (space: SpaceEntity) => {
|
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);
|
allDevices.push(...space.devices);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (space.children && space.children.length > 0) {
|
if (space.children?.length) {
|
||||||
for (const childSpace of space.children) {
|
for (const child of space.children) {
|
||||||
const fullChildSpace = await this.spaceRepository.findOne({
|
const fullChild = await this.spaceRepository.findOne({
|
||||||
where: { uuid: childSpace.uuid },
|
where: { uuid: child.uuid },
|
||||||
relations: ['children', 'devices', 'devices.productDevice'],
|
relations: ['children', 'devices', 'devices.productDevice'],
|
||||||
});
|
});
|
||||||
|
|
||||||
if (fullChildSpace) {
|
if (fullChild) {
|
||||||
await fetchSpaceDevices(fullChildSpace);
|
await fetchSpaceDevices(fullChild);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Start recursive fetch for all top-level spaces
|
|
||||||
for (const space of community.spaces) {
|
for (const space of community.spaces) {
|
||||||
const fullSpace = await this.spaceRepository.findOne({
|
await fetchSpaceDevices(space);
|
||||||
where: { uuid: space.uuid },
|
|
||||||
relations: ['children', 'devices', 'devices.productDevice'],
|
|
||||||
});
|
|
||||||
|
|
||||||
if (fullSpace) {
|
|
||||||
await fetchSpaceDevices(fullSpace);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return allDevices;
|
return allDevices;
|
||||||
|
Reference in New Issue
Block a user