The complete guide to Fastify plugin system
Understanding the Fastify Plugin System
What does it mean? This concept may seem trivial, but it is very powerful:
Each context can have its own state.
Each context can’t access the state of other contexts.
It is possible to create a context with the same code but different states.
Encapsulation and Inheritance
The encapsulation concept can be pushed to the extreme by adding the inheritance behaviour. In this case, the encapsulation is not only a mechanism to isolate the contexts, but also a mechanism to create a new context from others.
Here is a descriptive image:
As you can see, the root context is the parent of the two children contexts. This representation shows the tree structure of the application. But, what is the difference between each context?
If I would like to access the ctx1 decorator from the root context, I can’t do it, unless I break the encapsulation by wrapping the plugin function with the fastify-plugin module:
Now the application schema will look like this because we broke the ctx1 context, and the parent swallowed it:
Now, the app instance has access to the ctx1 decorator. Note that every plugin you will install will be wrapped with the fastify-plugin module, otherwise if the plugin adds a database connection, it will be encapsulated and inaccessible from the parent context!