@@ -2,23 +2,28 @@ import 'reflect-metadata';
22import { setupSwagger } from '@config/swagger.config' ;
33import fastifyCors from '@fastify/cors' ;
44import helmet from '@fastify/helmet' ;
5+ import { client } from '@infra/database/connection' ;
56import { initializeSentry } from '@infra/monitoring/sentry.config' ;
67import { ValidationPipe } from '@nestjs/common' ;
78import { NestFactory } from '@nestjs/core' ;
89import { FastifyAdapter , type NestFastifyApplication } from '@nestjs/platform-fastify' ;
910import { AppModule } from './app.module' ;
1011
12+ let app : NestFastifyApplication ;
13+
1114async function bootstrap ( ) {
1215 initializeSentry ( ) ;
1316
14- const app = await NestFactory . create < NestFastifyApplication > (
17+ app = await NestFactory . create < NestFastifyApplication > (
1518 AppModule ,
1619 new FastifyAdapter ( {
1720 logger : true ,
1821 trustProxy : true ,
1922 } ) ,
2023 ) ;
2124
25+ app . enableShutdownHooks ( ) ;
26+
2227 // biome-ignore lint/suspicious/noExplicitAny: Fastify plugin type compatibility with NestJS adapter
2328 await app . register ( helmet as any , {
2429 contentSecurityPolicy : {
@@ -62,8 +67,35 @@ async function bootstrap() {
6267 const port = Number ( process . env . PORT ) || 3001 ;
6368
6469 await app . listen ( port , '0.0.0.0' ) ;
70+
71+ console . log ( `Application is running on port ${ port } ` ) ;
6572}
6673
74+ async function gracefulShutdown ( signal : string ) {
75+ console . log ( `Received ${ signal } , starting graceful shutdown...` ) ;
76+
77+ try {
78+ if ( app ) {
79+ console . log ( 'Closing application...' ) ;
80+ await app . close ( ) ;
81+ console . log ( 'Application closed successfully' ) ;
82+ }
83+
84+ console . log ( 'Closing database connection...' ) ;
85+ await client . end ( ) ;
86+ console . log ( 'Database connection closed' ) ;
87+
88+ console . log ( 'Graceful shutdown completed' ) ;
89+ process . exit ( 0 ) ;
90+ } catch ( error ) {
91+ console . error ( 'Error during graceful shutdown:' , error ) ;
92+ process . exit ( 1 ) ;
93+ }
94+ }
95+
96+ process . on ( 'SIGTERM' , ( ) => gracefulShutdown ( 'SIGTERM' ) ) ;
97+ process . on ( 'SIGINT' , ( ) => gracefulShutdown ( 'SIGINT' ) ) ;
98+
6799bootstrap ( ) . catch ( ( error ) => {
68100 console . error ( 'Failed to start application:' , error ) ;
69101 process . exit ( 1 ) ;
0 commit comments