0

I needed a separate validation logic per version (prefix)

const routes = require('./routes/v1/users')
fastify.register(route, { prefix: `/v1` }) // currently using fastify@4.5.2

Might be good if there's something similar to below:

fastify.register(route, {
  prefix: `/v1`,
  preValidation: (req, reply) => { /* logic here */ }
})

Tried looking fastify docs, other channels and I can't find any similar implementation.

Redd.o
  • 147
  • 2
  • 5

1 Answers1

2

There is not such option to the fastify.register method, but you can do it playing with encapsulation.

You can create a dedicated context that includes your routes + the hook. This context will be isolated by other context you will create with register.

This example show you how:

const fastify = require('fastify')({ logger: false, exposeHeadRoutes: false })

async function run() {
  const route = function routesPlugin(fastify, options, next) {
    fastify.get('/hello', async (request, reply) => {
      console.log('request')
      return { hello: 'world' }
    })
    next()
  }

  fastify.register(function intermediatePlugin(instance, opts, next) {
    instance.addHook('preValidation', function hook(request, reply, done) {
      console.log('only for v1')
      done()
    })

    instance.register(route, { prefix: `/v1` })
    next()
  })

  fastify.register(route, { prefix: `/v2` })

  await fastify.inject('/v1/hello')
  await fastify.inject('/v2/hello')
}
run()

You can visualize this structure by using fastify-overview (and the fastify-overview-ui plugin together:

structure

Note that the hook is child of the intermediatePlugin that is not shared by the v2's routesPlugin sibling.

Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73