From dd831403926868f0319b82f54028fa76087f1566 Mon Sep 17 00:00:00 2001 From: Sonu Rauniyar Date: Thu, 12 Mar 2026 14:17:12 +0545 Subject: [PATCH] Completed adding graceful shutdown handler --- examples/basic-server.ts | 4 +++- src/index.ts | 20 +++++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/examples/basic-server.ts b/examples/basic-server.ts index e93c064..13afb29 100644 --- a/examples/basic-server.ts +++ b/examples/basic-server.ts @@ -1,4 +1,4 @@ -import { createServer } from '@linkforty/core'; +import { createServer, registerGracefulShutdown } from '@linkforty/core'; async function start() { const server = await createServer({ @@ -18,6 +18,8 @@ async function start() { host: '0.0.0.0', }); + registerGracefulShutdown(server); + console.log('LinkForty server running on http://localhost:3000'); console.log(''); console.log('API Endpoints:'); diff --git a/src/index.ts b/src/index.ts index c4d6ed0..41f372f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,7 +1,7 @@ import Fastify, { FastifyInstance } from 'fastify'; import cors from '@fastify/cors'; import redis from '@fastify/redis'; -import { initializeDatabase, DatabaseOptions } from './lib/database.js'; +import { initializeDatabase, DatabaseOptions, db } from './lib/database.js'; import { redirectRoutes } from './routes/redirect.js'; import { linkRoutes } from './routes/links.js'; import { analyticsRoutes } from './routes/analytics.js'; @@ -55,6 +55,24 @@ export async function createServer(options: ServerOptions = {}) { return fastify; } +export function registerGracefulShutdown(fastify: FastifyInstance): void { + const shutdown = async (signal: string) => { + fastify.log.info(`Received ${signal}, shutting down gracefully`); + try { + await fastify.close(); + await db.end(); + fastify.log.info('Shutdown complete'); + process.exit(0); + } catch (err) { + fastify.log.error(err, 'Error during shutdown'); + process.exit(1); + } + }; + + process.once('SIGTERM', () => shutdown('SIGTERM')); + process.once('SIGINT', () => shutdown('SIGINT')); +} + // Re-export utilities and types export * from './lib/utils.js'; export * from './lib/database.js';