본문 바로가기

programming/Javascript

Node-Sequelize-Mysql (4) Model 생성 & migrations 파일 생성

1. migrations 파일 & model 생성

sequelize model:generate --name Member --attributes name:string, password:string
  • DBMS에 적용하기 위한 migrations 파일이 만들어지고, ORM에서 객체로 사용할 memer.js 파일이 만들어진다

2. 생성된 migrations 파일에 필요한 컬럼 추가

"use strict";
module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable(
      "members",
      {
        id: {
          allowNull: false,
          autoIncrement: true,
          primaryKey: true,
          type: Sequelize.INTEGER,
        },
        name: {
          type: Sequelize.STRING(50),
          comment: "실명",
        },
        password: {
          type: Sequelize.STRING(512),
          comment: "비밀번호",
        },
        email: {
          type: Sequelize.STRING(100),
          allowNull: false,
          comment: "이메일",
        },
        is_deleted: {
          type: Sequelize.TINYINT.UNSIGNED,
          defaultValue: 0,
          comment: "삭제여부(0:아니오, 1:예)",
        },
        phone: {
          type: Sequelize.STRING(256),
          allowNull: false,
          comment: "휴대폰(010-XXXX-XXXX)",
        },
        created_at: {
          type: "TIMESTAMP",
          defaultValue: Sequelize.fn("NOW"),
          allowNull: false,
          comment: "등록일시",
        },
        updated_at: {
          type: "TIMESTAMP",
          defaultValue: Sequelize.literal(
            "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
          ),
          comment: "수정일시",
        },
      },
      {
        uniqueKeys: {
          phone_unique: {
            fields: ["phone"],
          },
        },
        comment: "회원",
      }
    );
  },
  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable("members");
  },
};

 

3-1. (수작업) 생성된 models/member.js 파일도 동일하게 column 작업

  • 생성한 migrations 파일과 동일하게 넣어준다

 

3-2. (반자동?) migrations 파일로 먼저 DB에 반영을 하고, 반영된 내용을 그대로 ORM Model로 가져온다 

 

  • models/member.js → sequelize-cli 명령어로 생성된 member 모델 파일 삭제
  • 작성한 migrations 파일 DBMS에 반영
npx sequeilize-cli db:migrate
  • sequelize-auto 설치
npm install -g -d sequelize-auto
  • sequelize-auto 실행 파일 작성
    • 프로젝트 루트 디렉토리에 /orm.js
const SequelizeAuto = require("sequelize-auto");

const auto = new SequelizeAuto("DB-SCHEMA", "root", "db-password", {
  host: "localhost",
  dialect: "mysql",
  directory: "./models",
  port: "db-port",
  caseModel: "c",
  caseFile: "c",
});

auto.run((err) => {
  if (err) throw err;
});
  1.  

 

  • node orm 파일 실행

 

  • orm - model을 자동으로 만들어준다 조금만 수정해서 사용하자
    • init-models.js 삭제
    • member.js → Member.js
      • 객체로 사용할 거라서 이름 변경하고,
      • 파일 수정
      • index에서 정의한 sequelize 객체 import
      • underscored : true 추가
import sequelize from "../index.js";
import { DataTypes } from "sequelize";

const Member = sequelize.define(
  "Member",
  {
    id: {
      autoIncrement: true,
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
    },
    type: {
      type: DataTypes.TINYINT.UNSIGNED,
      allowNull: false,
      comment: "회원 유형(0:관리자, 1:일반)",
    },
    name: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: "실명",
    },
    password: {
      type: DataTypes.STRING(512),
      allowNull: true,
      comment: "비밀번호",
    },
    email: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: "이메일",
    },
    phone: {
      type: DataTypes.STRING(256),
      allowNull: false,
      comment: "휴대폰(010-XXXX-XXXX)",
      unique: "phone_unique",
    },
    nickname: {
      type: DataTypes.STRING(80),
      allowNull: true,
      comment: "닉네임",
    },
    is_deleted: {
      type: DataTypes.TINYINT.UNSIGNED,
      allowNull: true,
      defaultValue: 0,
      comment: "삭제여부(0:아니오, 1:예)",
    },
    portrait_url: {
      type: DataTypes.STRING(256),
      allowNull: true,
      comment: "프로필 사진 S3 url",
    },
    marketing_agree: {
      type: DataTypes.TINYINT.UNSIGNED,
      allowNull: true,
      defaultValue: 0,
      comment: "마케팅 수신 동의여부(0: 아니오, 1: 예)",
    },
    last_login_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: sequelize.literal("CURRENT_TIMESTAMP"),
      comment: "마지막 로그인 일시",
    },
    login_fail_count: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: "로그인 실패 횟수",
    },
    password_reset_code: {
      type: DataTypes.STRING(256),
      allowNull: true,
      comment: "패스워드 재설정 인증코드",
    },
    withdraw_at: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: "탈퇴일시",
    },
  },
  {
    sequelize,
    tableName: "member",
    timestamps: true,
    indexes: [
      {
        name: "PRIMARY",
        unique: true,
        using: "BTREE",
        fields: [{ name: "id" }],
      },
      {
        name: "phone_unique",
        unique: true,
        using: "BTREE",
        fields: [{ name: "phone" }],
      },
    ],
    underscored: true,
  }
);

export default Member;

 

 

 

Node-Sequelize-Mysql (5) Jest 사용해서 만든 ORM 객체 테스트하기