How do I determine if a feature should be implemented by a hook, named middleware or a route handler?


#1

I am currently following the Adonis tutorial. So far, I can follow the concepts such as hooks, middleware and route handlers and know how to apply them.

If I am correct, all three methods mentioned above could perform the same functionality. However, I don’t really understand when I should use one instead the other. I was hoping you would have some rule of thumbs for what feature to implement with which method. Thank you, in advance!


#2

Hi there, I’m new to adonis too but I’ll answer your question just checking docs.

If it was, why would they be named it differently?

In short, Hooks are actions for database operation in a specified lifecycle event While middleware set of actions executed in sequence, one after the other in http lifecycle.

Hooks

Hooks are the actions you perform before or after a specified database operation.

From very first sentence from docs.

Adonis Hooks are similar to Vue.js hooks Vue.js Lifecycle Hooks.

You can check all lifecycle events as follows:

https://adonisjs.com/docs/4.1/database-hooks#_lifecycle_events

Hooks use cases

Password hashing

From docs

Hashing the user password before saving it to the database.

Email sending

Let’s assume, an user creates new account, after creating it, we want to send a mail to user for account verification. So we can create a hook to send email with afterCreate

Middleware

What Middleware can do?

Middleware can perform one/all of the following operations

  1. Decorate HTTP context and add values to it.
  2. Respond to a given request, without reaching the route action.
  3. Deny requests by throwing errors.

Use case

Show only authenticated users

Code blocks from docs.

Route
  .get('users/:id', 'UserController.show')
  .middleware(['auth'])

https://adonisjs.com/docs/4.1/middleware#_named_middleware