관리 메뉴

나의 개발일지(김지헌)

시퀄라이즈 hooks 사용해보기 본문

공부

시퀄라이즈 hooks 사용해보기

코딩이좋아요 2023. 4. 27. 12:57

시퀄라이즈 hooks란 생성 조회 업데이트 삭제 등 쿼리가 이루어지기 전이나 후에 실행 되는 함수 이다 model에서 사용하면 된다.

 

Hooks - Sequelize | The Node.js / io.js ORM for PostgreSQL, MySQL, SQLite and MSSQL

Mixin Hooks View code Hooks are function that are called before and after (bulk-) creation/updating/deletion and validation. Hooks can be added to you models in three ways: By specifying them as options in sequelize.define By calling hook() with a string a

sequelize.org

시퀄라이즈 훅은 시퀄라이즈에서 DB에 접근하기 전이나 접근 후에 실행 되는 메소드

(1)
  beforeBulkCreate(instances, options)
  beforeBulkDestroy(options)
  beforeBulkUpdate(options)
(2)
  beforeValidate(instance, options)

[... validation happens ...]

(3)
  afterValidate(instance, options)
  validationFailed(instance, options, error)
(4)
  beforeCreate(instance, options)
  beforeDestroy(instance, options)
  beforeUpdate(instance, options)
  beforeSave(instance, options)
  beforeUpsert(values, options)

[... creation/update/destruction happens ...]

(5)
  afterCreate(instance, options)
  afterDestroy(instance, options)
  afterUpdate(instance, options)
  afterSave(instance, options)
  afterUpsert(created, options)
(6)
  afterBulkCreate(instances, options)
  afterBulkDestroy(options)
  afterBulkUpdate(options)

업데이트 훅 실행시에 조회를 하고 업데이트를 실행하기 때문에

beforeFind, beforeFineOne, afterFind, afterFindOne이 먼저 실행 됨

hooks: {
        /* 생성 전에 실행 */
        beforeCreate: (record, options) => {
          hooks.createdDate(record);
        },
				 /* 생성 후에 실행 */
        afterCreate: (record, options) => {
          hooks.createdDate(record);
        },
				/* 업데이트 전에 실행 */
        beforeUpdate: (record, options) => {
          hooks.updatedDate(record);
        },
				/* 업데이트 전에 실행 */
        afterUpdate: (record, options) => {
          hooks.updatedDate(record);
        },
				/* 찾기 전에 실행 */
        beforeFind: (record, options) => {
          hooks.updatedDate(record);
        },
				/* 찾기 후에 실행 */
        afterFind: (record, options) => {
          hooks.updatedDate(record);
        },
				/* 찾기  전에 실행 */
        beforeFindAll: (record, options) => {
          hooks.updatedDate(record);
        },
				/* 찾기 후에 실행 */
        afterFindAll: (record, options) => {
          hooks.updatedDate(record);
        },
}

수정시 모델에 접근하는 API에 individualHooks : true를 설정해야 업데이트시 실행된다.

await models.table.update(body, {  
   where: {  }, 
   individualHooks: true
});