Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
Pass fastify instance to controllers at a top level

Rather than passing the fastify instance to every function, how can I pass it at a top level only once so its available to all functions in the controller?

// route file
import { FastifyPluginAsync } from 'fastify'

import RootController from '../root.controller'

const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
  fastify.get('/', RootController.index(fastify))
  fastify.get('/show', RootController.show(fastify))
}

export default root
// controller file
import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'

export default {
  index: (fastify: FastifyInstance) => async (request: FastifyRequest, reply: FastifyReply) => {
    const hugs = fastify.someSupport()

    reply.send({ status: 'ok', love: hugs })
  },

  show: (fastify: FastifyInstance) => async (request: FastifyRequest, reply: FastifyReply) => {
    const hugs = 'extra ' + fastify.someSupport()

    reply.send({ status: 'ok', love: hugs })
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The answer is a simple, mechanical refactoring using closures:

// controller file
import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'

export default async function installRootController(fastify: FastifyInstance, opts): Promise<void> {
  fastify.get('/', async (request: FastifyRequest, reply: FastifyReply) => {
    const hugs = fastify.someSupport()

    reply.send({ status: 'ok', love: hugs })
  });

  fastify.get('/show', async (request: FastifyRequest, reply: FastifyReply) => {
    const hugs = 'extra ' + fastify.someSupport()

    reply.send({ status: 'ok', love: hugs })
  });
};

The inner functions (the async handlers for / and /show) have access to fastify because it's accessible from lexical scope of the surrounding function. This enables you to encapsulate entire "controllers" as Fastify plugins, ready to install like so:


fastify.register(installRootController);

Note that the "routes" file now has no use.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda