나의 개발일지(김지헌)
시퀄라이즈 hooks 사용해보기 본문
시퀄라이즈 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
});
'공부' 카테고리의 다른 글
nginx 설정 (0) | 2023.07.27 |
---|---|
네이버 클라우드 server, Object Storage, global dns ,cdn+ 사용 해보기 (0) | 2023.05.24 |
route53 S3버킷으로 HTTP 도메인 리다이렉션하기 + 클라우드 프론트 (0) | 2023.04.18 |
nodemailer로 메일 보내기 (0) | 2023.04.06 |
Typedi로 api작성 해보기 (0) | 2023.04.06 |