7

I new to fastify framework for node.js, and I'm asking for what is the exact use of fastify-plugin because I can't get the the idea behind it. I tried some code with or without the plugin and I can't notice the difference. except for some behavior like :

1- I can override the decorator I initiate and wrapped it with fastify-plugin.

2- I can use and share the decorator with other registered plugins.

Momen Nano
  • 109
  • 4
  • If you don't see any need for this plugin, then why do you use it? – Nico Haase Apr 06 '20 at 07:08
  • 3
    I didn't say 'There is no need for this plugin', Im just asking for clarification.. because I don't think I understand it :) – Momen Nano Apr 06 '20 at 13:24
  • 2
    @NicoHaase Also, there are a few places in the documentation that recommend using the plugin without giving clear explanations why / what it does exactly. – bluenote10 Feb 16 '21 at 11:33

1 Answers1

13

The concept is this one:

  • every register call will create an encapsulated context
  • every register + fastify-plugin will not create an encapsulated context: you will stay in the same context where the register was called

An encapsulated context you will use:

  • all the hooks in the context and in its parent
  • all the decorators in the context and in its parent

Here a visualization:

encapsulation

so, if you add an onRequest hook in the root node (the blue one), all the routes will execute that hook.

if you add the onRequest hook in the green one instead, ONLY the routes defined in that context will use that hook.

EDIT: I wrote a blog post and a plugin to visualize the structure of a fastify application, so you can generate an image like this example. Checkout fastify-overview

Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73
  • 1
    awesome answer! – koo Apr 17 '21 at 08:54
  • Just to further clarify, If I'm understanding correctly, an `onRequest` hook registered in the purple node would effect the blue node's context and execute for all routes? Would a hook registered in the orange node likewise execute for for all routes since neither it nor the purple node have their own encapsulated context? More succinctly, is it sufficient to say that a plugin will effect the context of the first plugin within the selection of itself and it's ancestors which was **not** registered with fastify-plugin? – bosco May 27 '21 at 21:53