Sequelize默认开启individualHooks属性

2022-09-28 14:42:08 浏览数 (2)

在使用Sequelize进行开发中我们通常使用Hooks做一些数据表修改后的操作,但是很多时候一个接口会对多个数据表进行处理使得Hooks只会触发afterBulkDestroy之类的批量Hooks而afterDestroy不会响应。

文档中的解决方法是在对数据进行增删改时添加 individualHooks:true属性,但是很多时候我们使用到大量的事务,每次需要对很多个表进行很多次操作。所以我们需要对这个属性进行批量设置。

解决方法:
代码语言:javascript复制
const hooks = {
  beforeBulkDestroy(options: DestroyOptions<TypeAttributes | TagAttributes>) {
    options.individualHooks = true;
    return options;
  },
  afterDestroy(options: DestroyOptions<TypeAttributes | TagAttributes>) {
    console.log("有单个删除");
  },
};
export default hooks;

在对在指定的Hooks前执行的Hooks中我们就设置option.individualHooks=true,并且对option进行返回,在后面的函数执行时读取这个属性就等于true了。

完整代码:

1.编写初始化Hooks代码,使用Hooks监听数据表变化:

代码语言:javascript复制
function init<T = any, J = any>(callback: (modal: J, type: "create" | "update" | "delete") => any) {
  return {
    beforeBulkCreate(options: any) {
      options.individualHooks = true;
      return options;
    },
    afterCreate(instance: T, options: any) {
      if (options.transaction) {
        options.transaction?.afterCommit(() => {
          callback((instance as any).dataValues as unknown as J, "create");
        });
      } else {
        callback((instance as any).dataValues as unknown as J, "create");
      }
    },
    beforeBulkUpdate(options: any) {
      options.individualHooks = true;
      return options;
    },
    afterUpdate(instance: T, options: any) {
      if (options.transaction) {
        options.transaction?.afterCommit(() => {
          callback((instance as any).dataValues as unknown as J, "update");
        });
      } else {
        callback((instance as any).dataValues as unknown as J, "update");
      }
    },
    beforeBulkDestroy(options: any) {
      options.individualHooks = true;
      return options;
    },
    afterDestroy(instance: T, options: any) {
      if (options.transaction) {
        options.transaction?.afterCommit(() => {
          callback((instance as any).dataValues as unknown as J, "delete");
        });
      } else {
        callback((instance as any).dataValues as unknown as J, "delete");
      }
    },
  } as any;
}
export default init;

2.编写数据表变化会回调函数:

代码语言:javascript复制
import type { Article, ArticleAttributes } from "../models/init-models";
import init from "./utils/init";

export default init<Article, ArticleAttributes>((model, type) => {
  console.log(type, model);
});

3.在Model中赋值到hooks属性就可以了对应文档

0 人点赞