69 lines
1.7 KiB
JavaScript
69 lines
1.7 KiB
JavaScript
import Fastify from 'fastify';
|
|
import cors from '@fastify/cors';
|
|
import { config } from './config.js';
|
|
import { db } from './db/client.js';
|
|
|
|
const fastify = Fastify({
|
|
logger: {
|
|
level: config.logLevel,
|
|
...(config.nodeEnv === 'development' && {
|
|
transport: {
|
|
target: 'pino-pretty',
|
|
options: {
|
|
translateTime: 'HH:MM:ss.l',
|
|
ignore: 'pid,hostname',
|
|
singleLine: false,
|
|
},
|
|
},
|
|
}),
|
|
},
|
|
});
|
|
|
|
await fastify.register(cors, {
|
|
origin: (origin, cb) => {
|
|
if (!origin) return cb(null, true);
|
|
if (config.allowedOrigins.includes(origin)) return cb(null, true);
|
|
cb(new Error(`Origen no permitido por CORS: ${origin}`), false);
|
|
},
|
|
methods: ['GET', 'POST', 'PATCH', 'DELETE'],
|
|
credentials: true,
|
|
});
|
|
|
|
fastify.get('/api/health', async () => ({
|
|
status: 'ok',
|
|
timestamp: new Date().toISOString(),
|
|
uptime: process.uptime(),
|
|
}));
|
|
|
|
const shutdown = async (signal) => {
|
|
fastify.log.info({ signal }, 'Graceful shutdown iniciado');
|
|
try {
|
|
await fastify.close();
|
|
await db.end();
|
|
process.exit(0);
|
|
} catch (err) {
|
|
fastify.log.error(err, 'Error durante shutdown');
|
|
process.exit(1);
|
|
}
|
|
};
|
|
|
|
process.on('SIGINT', () => shutdown('SIGINT'));
|
|
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
|
|
const dbOk = await db.testConnection();
|
|
if (!dbOk) {
|
|
fastify.log.fatal('DB connection failed — abortando arranque');
|
|
process.exit(1);
|
|
}
|
|
fastify.log.info('DB connection OK');
|
|
|
|
fastify.decorate('db', db);
|
|
|
|
try {
|
|
const address = await fastify.listen({ port: config.apiPort, host: config.apiHost });
|
|
fastify.log.info(`Taboada API lista en ${address}`);
|
|
} catch (err) {
|
|
fastify.log.error(err);
|
|
process.exit(1);
|
|
}
|