Socialify

Folder ..

Viewing healthController.ts
70 lines (65 loc) • 2.2 KB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { Request, Response } from 'express';
import { getDatabaseStatus } from '../database/data-source';
import { taskManager } from '../tasks/TaskManager';
import Logger from '../utils/logger';

interface HealthStatus {
    status: 'healthy' | 'unhealthy';
    timestamp: string;
    uptime: number;
    memory: {
        used: number;
        total: number;
        free: number;
        usage: number;
    };
    database: {
        status: 'connected' | 'disconnected';
        lastChecked: string;
    };
    tasks: Record<string, {
        registered: boolean;
        running: boolean;
        lastRun?: Date;
        nextRun?: Date;
    }>;
}

export const getHealthStatus = async (_req: Request, res: Response): Promise<void> => {
    try {
        const memoryUsage = process.memoryUsage();
        const uptimeInSeconds = process.uptime();
        const dbStatus = await getDatabaseStatus();
        const tasksStatus = await taskManager.getAllTasksStatus();

        const status: HealthStatus = {
            status: dbStatus ? 'healthy' : 'unhealthy',
            timestamp: new Date().toISOString(),
            uptime: Math.floor(uptimeInSeconds),
            memory: {
                used: Math.round(memoryUsage.heapUsed / 1024 / 1024),
                total: Math.round(memoryUsage.heapTotal / 1024 / 1024),
                free: Math.round((memoryUsage.heapTotal - memoryUsage.heapUsed) / 1024 / 1024),
                usage: Math.round((memoryUsage.heapUsed / memoryUsage.heapTotal) * 100)
            },
            database: {
                status: dbStatus ? 'connected' : 'disconnected',
                lastChecked: new Date().toISOString()
            },
            tasks: tasksStatus
        };

        Logger.info('Health check performed', {
            timestamp: true,
            prefix: 'Health'
        });

        res.json(status);
    } catch (error) {
        Logger.error('Health check failed', {
            timestamp: true,
            prefix: 'Health'
        });
        Logger.debug(error as string);

        res.status(500).json({
            status: 'unhealthy',
            timestamp: new Date().toISOString(),
            error: 'Health check failed'
        });
    }
};