Skip to content

Instantly share code, notes, and snippets.

@kenriortega
Last active October 14, 2021 22:47
Show Gist options
  • Save kenriortega/361a2977345e36809a5b9d34a07fc8e7 to your computer and use it in GitHub Desktop.
Save kenriortega/361a2977345e36809a5b9d34a07fc8e7 to your computer and use it in GitHub Desktop.

Fastify Basic

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment