본문 바로가기
JavaScript/node.js

Sequelize paranoid(삭제-복구)

by nacjji 2022. 12. 24.
Paranoid

sequelize 의 paranoid 는 컴퓨터의 휴지통 개념처럼 데이터를 완전히 삭제하는게 아닌 삭제 후 복구가 가능하도록 새로운 필드 속 넣어 두는 것이다. 

models 설정
'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Posts extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
	//관계 설정 
    }
  }
  Posts.init(
    {
      postId: {
	//필드 속성 작성
      deletedAt: {
        allowNull: true,
        type: DataTypes.DATE,
      },
    },
    {
      sequelize,
      modelName: 'Posts',
      timestamps: true,
      paranoid: true,
    },
  );
  return Posts;
};
  • 게시글 작성에서 /models/posts.js 코드를 예로 들어보자. 
  • 처음 모델을 생성하고 마이그레이션을 하면 deletedAt 필드는 없는 상태이다.
  • deletedAt 에 타입만 설정한다. 
  • allowNull가 false라면 paranoid 는 적용되지 않는다. 
  • 하단에 timestamps : true 와 paranoid : true 를 추가했다. 
  • paranoid 속성을 부여할 때 timestamps 옵션이 false 라면 paranoid 는 적용되지 않는다.

 

migrations 생성
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('Posts', {
	// 필드 설정
      deletedAt: {
        allowNull: true,
        type: Sequelize.DATE,
      },
    });
  },
  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('Posts');
  },
};
  • migrations 폴더의 post 파일에도 동일하게 deletedAt 필드를 추가한다. 

 

  findAllPosts = async () => {
    return await this.postsModel.findAll({ paranoid: false });
  };
  
  
  // 조회 결과
{
  "postId": 1,
  "userId": 1,
  "title": "test",
  "content": "test2",
  "coverImage": "",
  "createdAt": "2022-12-24T11:11:59.000Z",
  "updatedAt": "2022-12-24T11:11:59.000Z",
  "deletedAt": "2022-12-24T11:12:17.000Z"
}
  • 전체 게시글을 조회할 때 paranoid : false 속성을 부여하면 삭제된 게시글까지 조회 가능하다. 
  • 조회를 할 경우 deletedAt 필드가 추가된 것을 볼 수 있다.

 

복구
router.get("/restore/:postId",async(req,res)=>{
    const {postId} = req.params
    await Posts.restore({{where:{postId}})
    return res.status(201).json({result : "게시글 복구"})
})

// 복구 결과
{
  "postId": 1,
  "userId": 1,
  "title": "test",
  "content": "test2",
  "coverImage": "",
  "createdAt": "2022-12-24T11:11:59.000Z",
  "updatedAt": "2022-12-24T11:11:59.000Z",
  "deletedAt": null
},
  • 복구는 삭제한 게시글의 postId 를 params 로 받아 해당 글을 restore 함수를 이용해 복구하면 된다.

'JavaScript > node.js' 카테고리의 다른 글

컨트롤러(Controller)  (0) 2022.12.10
아키텍쳐 패턴(Architecture Pattern)  (0) 2022.12.10
JWT  (0) 2022.12.08
Node.js, 파일 시스템 기능  (1) 2022.11.24
Node.js, node.j란?  (0) 2022.11.24