How to use Hapi decorate
Days ago, I want to improve performance to my boilerplate for Hapi + MongoDB apps. On this crusade, I came across an interesting feature in the Hapi documentation: Decorate.
This open my mind about how handle my throws in the source of my Hapi apps, and I want to share with you!
Previously I meet Decorate my implementation in controllers/xpto is something like this:
This is an extracted part of my controllers/user.js, the method GET will return the information about an single user.
But you can see in this case I need to import Boom and reply then every time I need to dispatch an error for User not found. And in every new controller import Boom again.
You can just make boom globally, and then just call where you want importing Boom once! — Some newbie Dev
Globally is not an options!
Decorate to the rescue!
As you can see above, I write my common errors in a file and export a Hapi's Plugin. We can just load this plugin in your server instance and call it on yours controllers like in this snippet:
Just more clean right?
More than you saw here
Decorates can do more than just implement a simple wrapper for errors in your controller. You can extend the request, reply and server interfaces just like you saw above.
Importing and load your plugin in one place and sharing it in your entire application with this simple function Decorate.
You can see more about this in Hapi Documentation here.
This awesome feature of Hapi is very helpful if you want to write less code and keep DRY in your mind for bind your focus on your Business.
This and another studies are based on my Boilerplate called Start Hapiness, if you have any suggestion for improve this project feel free to open an issue or a pull request, it is both much welcomed!