feat: base Fastify — config desde env, pool pg y GET /api/health
This commit is contained in:
1 parent
3de41571e1
commit
7b57fb317f
5 files changed
+1604
No files matched your search
Generated
+1405
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "taboada-becarios-api",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "API de control de entradas/salidas y horas de becarios (NFC/QR) para Taboada",
|
||||
"scripts": {
|
||||
"start": "node src/index.js",
|
||||
"dev": "node --watch src/index.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^11.2.0",
|
||||
"@fastify/rate-limit": "^11.1.0",
|
||||
"@fastify/secure-session": "^8.3.0",
|
||||
"argon2": "^0.44.0",
|
||||
"dotenv": "^17.4.2",
|
||||
"fastify": "^5.9.0",
|
||||
"pg": "^8.22.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"pino-pretty": "^13.1.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import dotenv from 'dotenv';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const envPath = path.resolve(__dirname, '../../.env');
|
||||
|
||||
dotenv.config({ path: envPath });
|
||||
|
||||
const requiredVars = [
|
||||
'POSTGRES_PASSWORD',
|
||||
'POSTGRES_DB',
|
||||
'POSTGRES_USER',
|
||||
'API_PORT',
|
||||
'SESSION_SECRET',
|
||||
'SUPERVISORA_USER',
|
||||
'SUPERVISORA_PASSWORD_INICIAL',
|
||||
];
|
||||
const missing = requiredVars.filter((key) => !process.env[key]);
|
||||
|
||||
if (missing.length > 0) {
|
||||
for (const key of missing) {
|
||||
console.error(`✗ Falta ${key} en .env`);
|
||||
}
|
||||
console.error(`\n Archivo esperado: ${envPath}`);
|
||||
console.error(` Copia .env.example → .env y rellena los valores.\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (process.env.SESSION_SECRET.length < 32) {
|
||||
console.error('✗ SESSION_SECRET debe tener al menos 32 caracteres');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
export const config = {
|
||||
nodeEnv: process.env.NODE_ENV || 'development',
|
||||
apiPort: Number(process.env.API_PORT),
|
||||
apiHost: process.env.API_HOST || '0.0.0.0',
|
||||
logLevel: process.env.LOG_LEVEL || 'info',
|
||||
db: {
|
||||
host: process.env.POSTGRES_HOST || 'localhost',
|
||||
port: Number(process.env.POSTGRES_PORT || 5432),
|
||||
database: process.env.POSTGRES_DB,
|
||||
user: process.env.POSTGRES_USER,
|
||||
password: process.env.POSTGRES_PASSWORD,
|
||||
},
|
||||
session: {
|
||||
secret: process.env.SESSION_SECRET,
|
||||
// Salt de derivación de clave de @fastify/secure-session (16 bytes exactos).
|
||||
// No es secreto: la seguridad depende de SESSION_SECRET.
|
||||
salt: 'taboada-becarios',
|
||||
cookieName: 'taboada_session',
|
||||
ttlSeconds: 12 * 60 * 60,
|
||||
cookieSecure: process.env.COOKIE_SECURE !== 'false',
|
||||
},
|
||||
supervisora: {
|
||||
usuario: process.env.SUPERVISORA_USER,
|
||||
passwordInicial: process.env.SUPERVISORA_PASSWORD_INICIAL,
|
||||
},
|
||||
maxHorasJornada: Number(process.env.MAX_HORAS_JORNADA || 12),
|
||||
allowedOrigins: (process.env.ALLOWED_ORIGINS || '')
|
||||
.split(',')
|
||||
.map((origin) => origin.trim())
|
||||
.filter(Boolean),
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
import pg from 'pg';
|
||||
import { config } from '../config.js';
|
||||
|
||||
const { Pool } = pg;
|
||||
|
||||
const pool = new Pool({
|
||||
host: config.db.host,
|
||||
port: config.db.port,
|
||||
database: config.db.database,
|
||||
user: config.db.user,
|
||||
password: config.db.password,
|
||||
max: 10,
|
||||
idleTimeoutMillis: 30000,
|
||||
connectionTimeoutMillis: 5000,
|
||||
});
|
||||
|
||||
pool.on('error', (err) => {
|
||||
console.error('[db] Error inesperado del pool:', err);
|
||||
});
|
||||
|
||||
export const db = {
|
||||
query(text, params) {
|
||||
return pool.query(text, params);
|
||||
},
|
||||
getClient() {
|
||||
return pool.connect();
|
||||
},
|
||||
end() {
|
||||
return pool.end();
|
||||
},
|
||||
async testConnection() {
|
||||
try {
|
||||
const res = await pool.query('SELECT 1 AS ok');
|
||||
return res.rows[0]?.ok === 1;
|
||||
} catch (err) {
|
||||
console.error('[db] testConnection falló:', err.message);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
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);
|
||||
}
|
||||
Reference in new issue
Block a user