All files / src/presentation/http/routes health.routes.ts

100% Statements 10/10
100% Branches 2/2
100% Functions 2/2
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                22x   22x                         103x 103x 101x 101x   2x 1x 1x             1x          
import type { App } from '../../../infrastructure/http/build-app';
import { CheckHealthUseCase } from '../../../application/health/check-health.use-case';
import { DatabaseUnavailableError } from '../../../domain/health/errors/database-unavailable.error';
import { PrismaHealthChecker } from '../../../infrastructure/health/prisma-health-checker';
import { prisma } from '../../../infrastructure/database/prisma-client';
import { healthySchema, unhealthySchema } from '../schemas/health.schema';
 
export async function healthRoutes(app: App) {
  const checkHealthUseCase = new CheckHealthUseCase(new PrismaHealthChecker(prisma));
 
  app.route({
    method: 'GET',
    url: '/health',
    schema: {
      tags: ['Health'],
      summary: 'Check API health',
      description: 'Verifies that the API process is running and that the PostgreSQL database is reachable.',
      response: {
        200: healthySchema,
        503: unhealthySchema,
      },
    },
    handler: async (request, reply) => {
      try {
        const report = await checkHealthUseCase.execute();
        request.log.info({ report }, 'health.check_succeeded');
        return reply.status(200).send(report);
      } catch (error) {
        if (error instanceof DatabaseUnavailableError) {
          request.log.error({ err: error }, 'health.check_failed');
          return reply.status(503).send({
            status: 'error',
            message: error.message,
            database: 'down',
          });
        }
 
        throw error;
      }
    },
  });
}