Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Accelerating Server-Side Development with Fastify

You're reading from   Accelerating Server-Side Development with Fastify A comprehensive guide to API development for building a scalable backend for your web apps

Arrow left icon
Product type Paperback
Published in Jun 2023
Publisher Packt
ISBN-13 9781800563582
Length 406 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (3):
Arrow left icon
Maksim Sinik Maksim Sinik
Author Profile Icon Maksim Sinik
Maksim Sinik
Matteo Collina Matteo Collina
Author Profile Icon Matteo Collina
Matteo Collina
Manuel Spigolon Manuel Spigolon
Author Profile Icon Manuel Spigolon
Manuel Spigolon
Arrow right icon
View More author details
Toc

Table of Contents (21) Chapters Close

Preface 1. Part 1:Fastify Basics
2. Chapter 1: What Is Fastify? FREE CHAPTER 3. Chapter 2: The Plugin System and the Boot Process 4. Chapter 3: Working with Routes 5. Chapter 4: Exploring Hooks 6. Chapter 5: Exploring Validation and Serialization 7. Part 2:Build a Real-World Project
8. Chapter 6: Project Structure and Configuration Management 9. Chapter 7: Building a RESTful API 10. Chapter 8: Authentication, Authorization, and File Handling 11. Chapter 9: Application Testing 12. Chapter 10: Deployment and Process Monitoring for a Healthy Application 13. Chapter 11: Meaningful Application Logging 14. Part 3:Advanced Topics
15. Chapter 12: From a Monolith to Microservices 16. Chapter 13: Performance Assessment and Improvement 17. Chapter 14: Developing a GraphQL API 18. Chapter 15: Type-Safe Fastify 19. Index 20. Other Books You May Enjoy

Adding a basic plugin instance

Previously, we talked about a plugin instance as a child component of an application instance.

To create one, you simply need to write the following:

app.register(function myPlugin(pluginInstance, opts, next) {
  pluginInstance.log.info('I am a plugin instance,
    children of app')
  next()
}, { hello: 'the opts object' })

These simple lines have just created an encapsulated context: this means that every event, hook, plugin, and decorator registered in the myPlugin function scope will remain inside that context and all its children. Optionally, you can provide an input object as a second parameter to the register function. This will propagate the input to the plugin’s opts parameter. If you move the plugin to another file, this will become extremely useful when sharing a configuration through files.

To see how the encapsulated context acts, we can investigate the output of the following example:

app.addHook('onRoute', buildHook('root')) // [1]
app.register(async function pluginOne(pluginInstance, opts)
{
  pluginInstance.addHook('onRoute', buildHook('pluginOne'))
    // [2]
  pluginInstance.get('/one', async () => 'one')
})
app.register(async function pluginTwo(pluginInstance, opts {
  pluginInstance.addHook('onRoute', buildHook('pluginTwo'))
    // [3]
  pluginInstance.get('/two', async () => 'two')
  pluginInstance.register(async function pluginThree(
  subPlugin, opts) {
    subPlugin.addHook('onRoute', buildHook('pluginThree'))
      // [4]
    subPlugin.get('/threee', async () => 'three')
  })
})
function buildHook(id) {
  return function hook(routeOptions) {
    console.log(`onRoute ${id} called from ${routeOptions
      .path}`)
  }
}

Running the preceding code will execute [2] and [4] just one time, because inside pluginOne and pluginThree, only one route has been registered, and each plugin has registered only one hook. The onRoute hook [1] is executed three times, instead. This happens because it has been added to the app instance, which is the parent scope of all the plugins. For this reason, the root hook will listen to the events of its context and to the children’s ones.

This feature comes with an endless list of benefits that you will “get to know” through this book. To better explain the bigger advantage of this feature, imagine every plugin as an isolated box that may contain other boxes, and so on, where the Root application instance is the primary container of all the plugins. The previous code can be schematized in this diagram:

Figure 1.2 – Encapsulated contexts

Figure 1.2 – Encapsulated contexts

The request is routed to the right endpoint (the square in the diagram), and it will trigger all the hooks registered on each plugin instance that include the destination handler.

Every box is self-contained, and it won’t affect the behavior of its other siblings, thus giving you the certainty that no issue affects parts of the application other than the one where it occurred. Furthermore, the system only executes the hook functions your routes need! This allows you and your team to work on different parts of the application without affecting each other or causing side effects. Furthermore, the isolation will give you a lot more control over what is happening at your endpoints. Just to give you an example: you can add a dedicated database connection for hot-paths in your code base without extra effort!

This plugin example has shown more clearly the Fastify plugin system in action. It should help you understand the difference between a root application instance and plugin instances. You now have an idea of how powerful the plugin system is and of the benefits it implements by design:

  • Encapsulation: All the hooks, plugins, and decorators added to the plugin are binded to the plugin context
  • Isolation: Every plugin instance is self-contained and doesn’t modify sibling plugins
  • Inheritance: A plugin inherits the configuration of the parent plugin

The plugin system will be discussed in depth in Chapter 2.

Now, we are ready to explore how to manage the different configuration types a Fastify application needs to work correctly.

You have been reading a chapter from
Accelerating Server-Side Development with Fastify
Published in: Jun 2023
Publisher: Packt
ISBN-13: 9781800563582
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime