Home 미니 블로그 만들기 - 07
Post
X

미니 블로그 만들기 - 07

Express 서버에 Sequelize를 적용해보자.


Sequelize 연동

먼저 Sequelize와 MySQL을 연동합니다.

  • 설치

    1
    
    npm i sequelize
    

src/models/sequelize/index.js

참고 글 : Sequelize

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//index.js

import Sequelize from "sequelize";

// 클래스를 불러옵니다.
import Post from "./posts.js";
import Comment from "./comments.js";

const config = {
  username: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_DATABASE,
  host: process.env.DB_HOST,
  dialect: "mysql",
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000,
  },
  logging: false, // Query log ON/OFF
};

const db = {};

// new Sequelize를 통해 MySQL 연결 객체를 생성합니다.
const sequelize = new Sequelize(
  config.database,
  config.username,
  config.password,
  config
);

// 연결객체를 나중에 재사용하기 위해 db.sequelize에 넣어줍니다.
db.sequelize = sequelize;

// 모델 클래스를 넣어줍니다.
db.Post = Post;
db.Comment = Comment;

// 모델 정의
Post.init(sequelize);
Comment.init(sequelize);

// 모델간의 관계 정의
Post.associate(db);
Comment.associate(db);

export default db;

모델 정의

테이블 명세서를 참고해 모델을 정의합니다.

참고 글 : 데이터 모델링

Post, Comment 모델을 정의하겠습니다.


posts.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { DataTypes, Model } from "sequelize";

class Post extends Model {
  static init(sequelize) {
    return super.init(
      {
        post_id: {
          type: DataTypes.INTEGER,
          primaryKey: true,
          autoIncrement: true,
          allowNull: false,
          // unique
          // defaultValue
          // validate
        },
        title: {
          type: DataTypes.STRING(40),
          allowNull: false,
        },
        content: {
          type: DataTypes.TEXT,
          allowNull: false,
        },
      },
      {
        sequelize, // Sequelize 인스턴스
        timestamps: false,
        paranoid: false,
        underscored: true,
        freezeTableName: true,
        ModelName: "Post",
        tableName: "posts",
      }
    );
  }

  static associate(db) {
    db.Post.hasMany(db.Comment, {
      foreignKey: "post_id",
      sourceKey: "post_id",
    });
  }
}

export default Post;

comments.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { DataTypes, Model } from "sequelize";

class Comment extends Model {
  static init(sequelize) {
    return super.init(
      {
        comment_id: {
          type: DataTypes.INTEGER,
          primaryKey: true,
          autoIncrement: true,
          allowNull: false,
          // unique
          // defaultValue
          // validate
        },
        content: {
          type: DataTypes.STRING(255),
          allowNull: false,
        },
      },
      {
        sequelize,
        timestamps: false,
        paranoid: false,
        underscored: true,
        freezeTableName: true,
        modelName: "Comment",
        tableName: "comments",
      }
    );
  }

  static associate(db) {
    db.Comment.belongsTo(db.Post, {
      foreignKey: "post_id",
      targetKey: "post_id",
    });
  }
}

export default Comment;

app.js 수정

app.js 파일에 sync()를 작성해 sequelize 모델을 mysql과 동기화합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import express from "express";
import "dotenv/config";
import bodyParser from "body-parser";
import postRouter from "./src/routes/route_post.js";
import db from "./src/models/sequelize/index.js";

const app = express();

app.set("port", process.env.PORT || 5000);

try {
  await db.sequelize.sync();

  console.log("데이터베이스 연결됨.");
} catch (err) {
  console.log(err);
}

// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// router
app.use("/board", postRouter);

app.listen(app.get("port"), () => {
  console.log("Server On");
});

model_post.js 수정

기존에 Query 작업을 수행했던 mysql2/promise 모듈을 sequelize 모듈로 변경합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 변경 전
import getConnection from "../config/db_pool.js";

class postStorage {
  static async getPosts() {
    try {
      const conn = await getConnection();

      const [rows] = await conn.query("SELECT * FROM posts");

      conn.release();

      return rows;
    } catch (err) {
      console.log(err);
    }
  }

  ...

  static async addComment(postId, content) {
    try {
      const conn = await getConnection();

      const [rows] = await conn.query("INSERT INTO comments (content, post_id) VALUE (?, ?)  ", [content, postId]);

      conn.release();

      return rows;
    } catch (err) {
      console.log(err);
    }
  }
}

export default postStorage;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// 변경 후
import db from "./sequelize/index.js";

const Post = db.Post,
  Comment = db.Comment;

class postStorage {
  static async getPosts() {
    try {
      const rows = await Post.findAll({});

      return rows;
    } catch (err) {
      console.log("에러 발생!!", err);
    }
  }

  static async getPostById(postId) {
    try {
      const rows = await Post.findAll({
        where: {
          post_id: postId,
        },
      });

      return rows;
    } catch (err) {
      console.log("에러 발생!!", err);
    }
  }

  static async addPost(title, content) {
    try {
      const rows = Post.create({
        title,
        content,
      });

      return rows;
    } catch (err) {
      console.log("에러 발생!!", err);
    }
  }

  static async deletePostById(postId) {
    try {
      const rows = Post.destroy({
        where: {
          post_id: postId,
        },
      });

      return rows;
    } catch (err) {
      console.log("에러 발생!!", err);
    }
  }

  static async getComments(postId) {
    try {
      const rows = Comment.findAll({
        where: {
          post_id: postId,
        },
      });

      return rows;
    } catch (err) {
      console.log("에러 발생!!", err);
    }
  }

  static async addComment(postId, content) {
    try {
      const rows = Comment.create({
        content,
        post_id: postId,
      });

      return rows;
    } catch (err) {
      console.log("에러 발생!!", err);
    }
  }
}

export default postStorage;
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.