mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-10 15:17:41 +00:00
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(
|
||||
communityUuid: string,
|
||||
): Promise<DeviceEntity[]> {
|
||||
// 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<string>();
|
||||
|
||||
// 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;
|
||||
|
Reference in New Issue
Block a user