totolist/app.js
2025-08-28 13:57:06 +02:00

103 lines
No EOL
2.6 KiB
JavaScript

// server.js
const path = require('path');
const Fastify = require('fastify');
const formBody = require('@fastify/formbody');
const fastifyStatic = require('@fastify/static');
const fastifyView = require('@fastify/view');
const ejs = require('ejs');
const promClient = require('prom-client');
const fastifyCookie = require('@fastify/cookie');
const fastifySession = require('@fastify/session');
// --- App Instance ---
const app = Fastify({ logger: true });
// --- Plugins ---
app.register(formBody);
app.register(fastifyCookie);
app.register(fastifySession, {
secret: 'this_very_long_random_secret_32_chars_minimum!',
cookie: { secure: false },
saveUninitialized: false,
});
app.register(fastifyStatic, {
root: path.join(__dirname, 'public'),
prefix: '/static/',
});
app.register(fastifyView, {
engine: { ejs },
root: path.join(__dirname, 'views'),
layout: 'layout.ejs',
});
// --- Prometheus Metrics ---
const register = new promClient.Registry();
promClient.collectDefaultMetrics({ register });
const counterCreated = new promClient.Counter({
name: 'todo_created_total',
help: 'Nombre total de todos créés',
});
const counterDeleted = new promClient.Counter({
name: 'todo_deleted_total',
help: 'Nombre total de todos supprimés',
});
const gaugeCount = new promClient.Gauge({
name: 'todo_count',
help: 'Nombre courant de todos',
});
register.registerMetric(counterCreated);
register.registerMetric(counterDeleted);
register.registerMetric(gaugeCount);
const fastifySwagger = require('@fastify/swagger');
const fastifySwaggerUI = require('@fastify/swagger-ui');
// --- Swagger ---
app.register(fastifySwagger, {
openapi: {
info: {
title: 'Todo API',
version: '1.0.0',
description: 'CRUD de Todo en Fastify (Node.js) + SQLite',
},
servers: [{ url: 'http://localhost:3000' }],
},
});
app.register(fastifySwaggerUI, {
routePrefix: '/api/docs',
uiConfig: {
docExpansion: 'full',
deepLinking: false
}
});
// --- Routes ---
app.register(require('./routes/api'), {
promRegister: register,
counterCreated,
counterDeleted,
gaugeCount,
});
app.register(require('./routes/ui'), {
counterCreated,
counterDeleted,
gaugeCount,
});
app.register(require('./routes/other'), {
promRegister: register,
});
// --- Start Server ---
async function start() {
try {
await app.ready();
app.swagger();
await app.listen({ port: 3000, host: 'localhost' });
app.log.info('Server listening on http://localhost:3000');
} catch (err) {
app.log.error(err);
process.exit(1);
}
}
start();