Sequelize Counter Cache Patch

Ever since v4 of Sequelize, the counterCache plugin has been removed. The counterCache plugin allowed you to count associations of a parent model model automatically. For example, you may have an author model and want to keep track of how many books they have directly on the model to avoid n+1 queries in your application.
The Sequelize change log says that they removed counterCache because it can easily be achieved through the use of hooks; so here is a quick snippet of code you can use to add the functionality back into your Sequelize apps using said hooks.
Helper.
Create a helper function that you can easily attach to all your models as a hook.
This helper function will acts as a hook to be applied to all of your models and will look for any models that have counter columns based on the model being created / updated / destroyed and then recomputed those values.
Global Hooks.
Next, take the newly created hook and set it up as a global hook for every model in your application.
// src/models/index.js...import counterCache from 'src/helpers/counterCache';...sequelize.addHook('afterCreate', counterCache(db));
sequelize.addHook('afterUpdate', counterCache(db));
sequelize.addHook('afterDestroy', counterCache(db));
Now any time a model performs a create, update, or destroy lifecycle event, your hook will be called and all counter cache columns involving the instance will be recomputed.
Cache Columns.
Finally, define your cache columns on any models. For instance, you may have an author model and want a cache column for the number of published books they have.
export default (sequelize, DataTypes) => sequelize.define('Author',
{
books_published_count: {
type: DataTypes.INTEGER,
},
},
{
cacheColumns: {
column: 'books_published_count',
model: 'Book',
foreignKey: 'author_id',
where: {
state: 'published',
},
}
}
);You can see how this counter cache is actually a “scoped” counter cache as it also makes use of the where clause.
That’s it! You now have counter caching functionality across your Sequelize application again.

