Refactor automation and scene fetching to handle errors and improve readability

This commit is contained in:
faris Aljohari
2025-01-28 19:12:31 -06:00
parent 8161e8469b
commit 2477f4825e
2 changed files with 53 additions and 48 deletions

View File

@ -198,8 +198,7 @@ export class AutomationService {
async getAutomationBySpace(spaceUuid: string) {
try {
const space = await this.getSpaceByUuid(spaceUuid);
// Fetch automation data from the repository
const automationData = await this.automationRepository.find({
where: {
space: { uuid: spaceUuid },
@ -208,45 +207,47 @@ export class AutomationService {
relations: ['space'],
});
if (!space.spaceTuyaUuid) {
throw new BadRequestException(`Invalid space UUID ${spaceUuid}`);
}
const automations = await Promise.all(
automationData.map(async (automation) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const automationDetails = await this.tuyaService.getSceneRule(
// Safe fetch function to handle individual automation fetching
const safeFetch = async (automation: any) => {
try {
const automationDetails = (await this.tuyaService.getSceneRule(
automation.automationTuyaUuid,
);
)) as { result?: { name?: string; status?: string } }; // Explicit type assertion
if (
!automationDetails?.result?.name ||
automationDetails.result.name.startsWith(AUTO_PREFIX)
) {
return null; // Skip invalid or auto-generated automations
}
return {
uuid: automation.uuid,
...automationDetails,
};
}),
);
return automations
.filter(
(item: any) =>
item.result.name && !item.result.name.startsWith(AUTO_PREFIX),
)
.map((item: any) => {
return {
uuid: item.uuid,
name: item.result.name,
status: item.result.status,
name: automationDetails.result.name,
status: automationDetails.result.status,
type: AUTOMATION_TYPE,
};
});
} catch (error) {
console.warn(
`Skipping automation with UUID: ${automation.uuid} due to error. ${error.message}`,
);
return null;
}
};
// Process automations using safeFetch
const automations = await Promise.all(automationData.map(safeFetch));
return automations.filter(Boolean); // Remove null values
} catch (err) {
console.error('Error retrieving automations:', err);
if (err instanceof BadRequestException) {
throw err; // Re-throw BadRequestException
} else {
throw new HttpException(
err.message || 'Automation not found',
err.status || HttpStatus.NOT_FOUND,
);
throw err;
}
throw new HttpException(
err.message || 'Automation not found',
err.status || HttpStatus.NOT_FOUND,
);
}
}
async findAutomationBySpace(spaceUuid: string) {