Servicio rest con fastify cors, helmet, rate limit, autoload
import Fastify from 'fastify'
import { dirname, join } from 'path'
import { fileURLToPath } from 'url'
import AutoLoad from 'fastify-autoload'
import RateLimit from 'fastify-rate-limit'
import Helmet from 'fastify-helmet'
import cors from 'fastify-cors'
const fastify = Fastify({
logger: true
})
const port = process.env.PORT ?? 5000
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
fastify
.register(Helmet)
.register(cors)
.register(RateLimit, {
global: true,
max: 5
})
.register(AutoLoad, {
dir: join(__dirname, "routes")
})
Definir las rutas para el micro servicio
fastify.get('/stats', async function (request, reply) {
return {
stats: {
cpu: process.cpuUsage(),
pid: process.pid,
platform: process.platform,
memoryUsage: process.memoryUsage()
}
}
})
Ejecutar el servidor en el PORT definido
fastify.listen(port, () => {
fastify.log.info(`server running on ${port}`)
})
Cerrar el servidor ante los eventos SIGINT/SIGTERM
async function closeGracefully(signal) {
console.log(`*^!@4=> Received signal to terminate: ${signal}`)
await fastify.close()
// await db.close() if we have a db connection in this app
// await other things we should cleanup nicely
process.exit()
}
process.on('SIGINT', await closeGracefully)
process.on('SIGTERM', await closeGracefully)