78 lines
2.7 KiB
TypeScript
78 lines
2.7 KiB
TypeScript
import axios from 'axios';
|
|
import { AppError, type Proyecto, RepositoryError } from '../domain/common.js';
|
|
import { MonitorRepository } from '../repository/monitor-repository.js';
|
|
|
|
export class MonitorUsecases {
|
|
constructor(private repository: MonitorRepository) {}
|
|
|
|
private async checkProjectAndSaveStatus(project: Proyecto): Promise<void> {
|
|
let status: Proyecto['estado_codigo'] = 'OK';
|
|
try {
|
|
await axios.get(project.url_health, { timeout: 5000, validateStatus: (s) => s === 200 });
|
|
} catch (e) {
|
|
const axiosError = e as { code?: string };
|
|
status = axiosError.code === 'ECONNABORTED' ? 'TIMEOUT' : 'ERROR';
|
|
}
|
|
|
|
await this.repository.saveProjectStatus(project.id, status);
|
|
}
|
|
|
|
async checkAllProjectsHealth(): Promise<void> {
|
|
try {
|
|
const projects = await this.repository.getProjects();
|
|
const checks = projects.map((project) => this.checkProjectAndSaveStatus(project));
|
|
|
|
await Promise.allSettled(checks);
|
|
} catch (err) {
|
|
throw new RepositoryError('Fallo masivo en el chequeo de salud', {
|
|
cause: err instanceof Error ? err.message : String(err)
|
|
});
|
|
}
|
|
}
|
|
|
|
async getDashboardData(): Promise<Proyecto[]> {
|
|
try {
|
|
return await this.repository.getDashboardData();
|
|
} catch (err) {
|
|
throw new RepositoryError('Error al recuperar datos del dashboard', {
|
|
cause: err instanceof Error ? err.message : String(err)
|
|
});
|
|
}
|
|
}
|
|
|
|
async createNewProject(nombre: string, urlHealth: string): Promise<void> {
|
|
const trimmedNombre = typeof nombre === 'string' ? nombre.trim() : '';
|
|
const trimmedUrl = typeof urlHealth === 'string' ? urlHealth.trim() : '';
|
|
|
|
if (trimmedNombre === '') {
|
|
throw new AppError('El nombre del proyecto es obligatorio', 400);
|
|
}
|
|
|
|
if (trimmedNombre.length > 100) {
|
|
throw new AppError('El nombre del proyecto no puede superar los 100 caracteres', 400);
|
|
}
|
|
|
|
if (trimmedUrl === '') {
|
|
throw new AppError('La URL de health check es obligatoria', 400);
|
|
}
|
|
|
|
try {
|
|
new URL(trimmedUrl);
|
|
} catch {
|
|
throw new AppError('La URL de health check no es valida', 400);
|
|
}
|
|
|
|
await this.repository.addProject(trimmedNombre, trimmedUrl);
|
|
}
|
|
|
|
async checkProjectHealth(projectId: number): Promise<void> {
|
|
const project = await this.repository.getProjectById(projectId);
|
|
if (!project) {
|
|
throw new AppError('Proyecto no encontrado', 404);
|
|
}
|
|
|
|
await this.checkProjectAndSaveStatus(project);
|
|
}
|
|
}
|
|
|