Pass fastify instance to controllers at a top level

Viewed 1147

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 })
  }
}
1 Answers

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.

Related