In the above figure, there are several entities:
- The root context
- Three root plugins
Given that everything in Fastify is a plugin, except for the root context, every “context” and “plugin” in this example is a plugin that can consist of decorators, hooks, plugins, and routes. Thus, to put this example into concrete terms, consider a basic scenario of a REST API server that has three routes: the first route () requires authentication, the second route (/two
) does not, and the third route (/three
) has access to the same context as the second route. Using to provide the authentication, the code for this example is as follows:
The above server example shows all of the encapsulation concepts outlined in the original diagram:
- Only the
authenticatedContext
has access to thefastify-bearer-auth
plugin. - Both the
publicContext
andgrandchildContext
have access to thefoo
request decorator. - Only the has access to the
bar
request decorator.
Sharing Between Contexts
Notice that each context in the prior example inherits only from the parent contexts. Parent contexts cannot access any entities within their descendent contexts. This default is occasionally not desired. In such cases, the encapsulation context can be broken through the usage of such that anything registered in a descendent context is available to the containing parent context.
Assuming the publicContext
needs access to the bar
decorator defined within the grandchildContext
in the previous example, the code can be rewritten to: