yonathan06 / fastify-now

File based routing for fastify https://github.com/fastify/fastify
MIT License
72 stars 8 forks source link

How can I get the fastify instance inside a function handler? #12

Closed barenko closed 3 years ago

barenko commented 3 years ago

I have the follow function in the routes/index.js file. How can I get the same fastify server instance that the fastify-now was registered?

module.exports.GET = async (req, res) => {
    await fastifyServer.db.connect();
    ...
    res.send({ hello: 'world' })
}
mandaputtra commented 3 years ago

You can use, this. It will refer to Fastify instance.

yonathan06 commented 3 years ago

@mandaputtra is right, but you will need to declare a function using the function keyword in order to have the right context bound to it.

module.exports.GET = async function getWorld(req, res) {
    // this = fastify instance
    await this.db.connect();
    ...
 }