Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion examples/basic-server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createServer } from '@linkforty/core';
import { createServer, registerGracefulShutdown } from '@linkforty/core';

async function start() {
const server = await createServer({
Expand All @@ -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:');
Expand Down
20 changes: 19 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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';
Expand Down
Loading