first commit
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { HealthController } from './health.controller';
|
||||
import { HealthService } from './health.service';
|
||||
|
||||
describe('HealthController', () => {
|
||||
let controller: HealthController;
|
||||
const checkMock = jest.fn().mockResolvedValue({
|
||||
status: 'ok',
|
||||
timestamp: new Date().toISOString(),
|
||||
database: 'up',
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [HealthController],
|
||||
providers: [
|
||||
{
|
||||
provide: HealthService,
|
||||
useValue: { check: checkMock },
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<HealthController>(HealthController);
|
||||
});
|
||||
|
||||
it('deve retornar status ok e database up', async () => {
|
||||
const result = await controller.check();
|
||||
|
||||
expect(checkMock).toHaveBeenCalled();
|
||||
expect(result.status).toBe('ok');
|
||||
expect(result.database).toBe('up');
|
||||
expect(result.timestamp).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { HealthService, HealthStatus } from './health.service';
|
||||
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
constructor(private readonly healthService: HealthService) {}
|
||||
|
||||
@Get()
|
||||
check(): Promise<HealthStatus> {
|
||||
return this.healthService.check();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller';
|
||||
import { HealthService } from './health.service';
|
||||
|
||||
@Module({
|
||||
controllers: [HealthController],
|
||||
providers: [HealthService],
|
||||
})
|
||||
export class HealthModule {}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '../../config/prisma.service';
|
||||
|
||||
export interface HealthStatus {
|
||||
status: 'ok' | 'error';
|
||||
timestamp: string;
|
||||
database: 'up' | 'down';
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class HealthService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async check(): Promise<HealthStatus> {
|
||||
const database = await this.checkDatabase();
|
||||
|
||||
return {
|
||||
status: database === 'up' ? 'ok' : 'error',
|
||||
timestamp: new Date().toISOString(),
|
||||
database,
|
||||
};
|
||||
}
|
||||
|
||||
private async checkDatabase(): Promise<'up' | 'down'> {
|
||||
try {
|
||||
await this.prisma.$queryRaw`SELECT 1`;
|
||||
return 'up';
|
||||
} catch {
|
||||
return 'down';
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user