Sling Academy
Home/Node.js/How to Use Hooks in Sequelize.js

How to Use Hooks in Sequelize.js

Last updated: December 29, 2023

Hooks (also known as lifecycle events) are functions which are called before and after calls in sequelize are executed. In this tutorial, we will go through an understanding of what hooks are in Sequelize.js and how to use them effectively to enhance your application’s models with custom behavior.

Understanding Hooks in Sequelize

Sequelize.js offers a wide array of hooks that allow you to tap into various points in the lifecycle of a database query. These include moments before an instance is validated, saved, updated, or destroyed, among others.

// Example of a beforeValidate hook for a User model
sequelize.define('User', {
  username: Sequelize.STRING,
  email: Sequelize.STRING
}, {
  hooks: {
    beforeValidate: (user, options) => {
      // custom code here
    }
  }
});

Using Basic Hooks

Let’s start with how to declare and use basic hooks. We will define a beforeCreate hook that modifies a user’s email before the user is created.

sequelize.define('User', {
  username: Sequelize.STRING,
  email: Sequelize.STRING
}, {
  hooks: {
    beforeCreate: (user, options) => {
      user.email = user.email.toLowerCase();
    }
  }
});

Asynchronous Hooks

In reality, most hooks will perform asynchronous operations. Sequelize supports both promise-based and async/await syntax for hooks.

sequelize.define('User', {
  username: Sequelize.STRING,
  email: Sequelize.STRING
}, {
  hooks: {
    beforeSave: async (user, options) => {
      user.email = await someAsyncFunction(user.email);
    }
  }
});

Advanced Hook Usage

Now let’s move on to more advanced usage of hooks. We will use a combination of hooks to maintain the state of an associated model.

// ... other code ...
User.addHook('afterCreate', async (user, options) => {
  await Log.create({ event: 'User Created', userId: user.id });
});

User.addHook('beforeDestroy', async (user, options) => {
  await user.update({ isActive: false });
});

Error Handling in Hooks

Error handling is a critical part of working with hooks. When a hook throws an error, the action that triggered the hook gets reverted.

// ... other code ...
User.addHook('beforeSave', (user, options) => {
  if (!user.username) {
    throw new Error('Username is required!');
  }
});

Order of Execution for Hooks

It’s also important to understand the order in which hooks execute, particularly when you have multiple hooks of the same type.

// ... other code ...
User.addHook('beforeSave', 'checkUsername', (user, options) => {
  // First hook
});
User.addHook('beforeSave', 'checkEmail', (user, options) => {
  // Second hook
});

Disabling Hooks

There might be scenarios where you would need to temporarily disable a hook during a certain call. This can be achieved using the individualHooks option.

// ... other code ...
User.update({ email: '[email protected]' }, { individualHooks: false });

Conclusion

In this guide, we have covered the basics of using hooks in Sequelize.js, advanced scenarios, and error handling. Understanding and implementing hooks in your applications can greatly improve the functionality and reliability of your models.

Next Article: Sequelize.js: Optimize Queries to Boost Performance

Previous Article: Using afterDelete and afterDestroy Hooks in Sequelize.js

Series: Sequelize.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates