Skip to content

Use cases for intent based CRUD hooks

Miroslav Bajtoš edited this page Mar 9, 2015 · 14 revisions

We recently received some feedbacks on the intent-based CRUD hooks.

There are issues and ideas raised. We would like to fully understand the use cases to decide what's the best way to enhance the hook apis, especially the ctx structure. Community input is critical to make the exercise successful. Please contribute your use cases below.

GitHub wiki does not support comments, let's keep the discussion in https://github.com/strongloop/loopback-datasource-juggler/issues/482.


There are different types of methods that trigger a hook function:

  1. prototype methods, such as updateAttributes, save, and delete. They work on a given model instance.
  2. static methods, such as create, updateAll, and deleteAll. They work on the a given model class.

A different taxonomy taking into account the database operation being performed:

  1. Methods that perform a full update of a single instance, i.e. they have all instance properties available and use them to replace the current data in the database. This includes both prototype methods like "save" and static methods like "create".

  2. Methods that perform a partial update of a single instance, i.e. "prototype.updateAttributes".

  3. Methods that perform a partial update of multiple instances, i.e. "updateAll".

  4. Methods that remove a single instance, i.e. "deleteById", "prototype.remove".

  5. Methods that perform a batch delete using a query - "deleteAll".

There are different purposes for hooks that @raymondfeng can see:

  1. In a before hook, perform additional operations.
  2. In a before hook, run some validations and fail fast.
  3. In a before hook, change/transform the input to the target DB operation.
  4. In a after hook, perform additional operations based on the outcome of the CRUD.
  5. In a after hook, change/transform the output from the target DB operation so that the callback/promise will receive a modified result.

Hooks typically need to read some information from the ctx object and write some information back to hook to influence downstream operations (another hook, the target method or error handler).

Use cases from Raymond:

  • Calculate a license key for a subscription record before it's save to the DB. The license key is derived from multiple properties of the subscription, such as userId, product, and expiration date.
  • Automatically set the created and modified timestamps depending on if the intent is to create or update.
  • Hash the password for the user record.
  • Perform cascade deletion

Use cases from Fabien:

Use cases from Benjamin B:

  • Soft deletes
  • Operations based on changed attributes (after hook using the something like the new hookState)
  • De-normalization,
Clone this wiki locally