I read the docs, but I still don't understand how I'm supposed to split my routes so that only some plugins apply to them.
Here's what I've got:
index.ts
import fastify from 'fastify'
import bookingsRoutes from './routes/bookings'
const server = fastify({
logger: process.env.NODE_ENV !== 'production',
trustProxy: '64.225.88.57', // DigitalOcean load balancer
})
server.get('/health', (_, reply) => {
reply.send("OK")
})
server.register(bookingsRoutes)
server.listen(process.env.PORT || 3000, '0.0.0.0', (err, address) => {
if (err) {
server.log.error(err)
process.exit(1)
}
server.log.info(`Server listening at ${address}`)
})
bookings.ts
// ...
const plugin: FastifyPluginAsync = async api => {
await Promise.all([
api.register(dbPlugin),
api.register(authPlugin),
])
const {db,log} = api
api.route<{Body:BookingRequestType,Reply:BookingType}>({
url: '/bookings',
method: 'POST',
async handler(req, res) {
console.log('got user',req.user)
}
})
}
export default fp(plugin, '3.x')
I thought by registering dbPlugin
and authPlugin
inside the booking routes plugin that it would only apply to those routes, but that doesn't seem to be right. It seems to be applying to /health
too.
Also not sure if I should be await
ing the 2 register functions like that but they return promises and that seems to be the only way to get the db
object back out of them...
What's the proper way to do this?