Understanding encapsulation
So far, we’ve written a few plugins. We are pretty confident about how they are structured and what arguments a plugin receives. We still need to discuss one missing thing about them – the concept of encapsulation.
Let’s recall the plugin function definition signature:
async function myPlugin(fastify, options)
As we know at this point, the first parameter is a Fastify instance. This instance is a newly created one that inherits from the outside scope. Let’s suppose something has been added to the root instance, for example, using a decorator. In that case, it will be attached to the plugin’s Fastify instance, and it will be usable as if it is defined inside the current plugin.
The opposite isn’t true, though. If we add functionalities inside a plugin, those things will be visible only in the current plugin’s context.
Context versus scope
Firstly, let’s take a look at the definitions...