49
loading...
This website collects cookies to deliver better user experience
fastify
and options
as inputs.function pluginA(fastify, options, done) {
// ...
done()
}
async function pluginB(fastify, options) {
// ...
}
import Fastify from 'fastify'
const fastify = Fastify()
fastify
.register(pluginA)
.register(pluginB)
import Fastify from 'fastify'
const fastify = Fastify()
fastify
.register(function pluginA(fastify, options, done) {
// Add a random number to fastify instance
fastify.decorate('rand', Math.random())
console.log(fastify.rand) // Accessible here
done()
})
.register(function pluginB(fastify, options, done) {
// Try to access the random number added in pluginA
console.log(fastify.rand) // undefined
done()
})
fastify-plugin
package to register a plugin to the main Fastify instance.import Fastify from 'fastify'
import fp from 'fastify-plugin'
const fastify = Fastify()
fastify
// Register pluginA with fastify-plugin
.register(fp(function pluginA(fastify, options, done) {
// Add a random number to fastify instance
fastify.decorate('rand', Math.random())
console.log(fastify.rand) // Accessible here
done()
}))
.register(function pluginB(fastify, options, done) {
// Try to access the random number added in pluginA
console.log(fastify.rand) // Also accessible here
done()
})
fastify-postgres
, fastify-mongodb
, fastify-redis
, ... they all use fastify-plugin
so you won't have to register them with fastify-plugin
.const pg = require('pg')
const fp = require('fastify-plugin')
function fastifyPostgres(fastify, options, next) {
const pool = new pg.Pool(options)
const db = {
connect: pool.connect.bind(pool),
pool: pool,
Client: pg.Client,
query: pool.query.bind(pool),
transact: transact.bind(pool)
}
// Inject postgres connection to Fastify instance
fastify.decorate('pg', db)
next()
}
module.exports = fp(fastifyPostgres)
// index.js
import Fastify from 'fastify'
import pg from 'fastify-postgres'
import routes from './routes.js'
const fastify = Fastify()
fastify
.register(pg, {
connectionString: 'postgres://postgres@localhost/postgres'
})
.register(routes)
fastify.pg
there:// routes.js
export default function routes(fastify, options, done) {
fastify.route({
method: 'GET',
url: '/',
handler: (req, reply) => {
// Have access to fastify.pg here
}
})
done()
}
fastify
I need to use the this
keyword.NOTE: Normal functions must be used rather than arrow functions to define route handlers. Read more here.
// routes.js
import { mainHandler } from './handlers.js'
export default function routes(fastify, options, done) {
fastify.route({
method: 'GET',
url: '/',
handler: mainHandler
})
done()
}
// handlers.js
export function mainHandler(req, reply) {
// Have access to this.pg here
}