Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
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
Tags
more
Archives
Today
Total
관리 메뉴

개발공부일지

NodeJS - DTO 본문

NodeJS

NodeJS - DTO

보람- 2023. 10. 24. 17:59

목차

1. 설정하기

2. Sequelize 사용

3. DTO

4. create


 

 

 

1. 설정하기

 

- 드라이버 설치하기

npm init -y
npm install express cors sequelize mysql2 dotenv

 

- index.js / app.js / route.js

- user → user.route / user.controller / user.service

- constants → db / index →  entity → user.entity

- dto.js → user.dto

 

 

 

 

 

2. Sequelize 사용

- entity.js 파일에서 db와 connection (dotenv를 사용해서)

- user.entity.js 파일에서 sequelize.define() 필드와 속성 지정

 

 

 

 

 

3. DTO

- Data Transfer Object 데이터를 전송하는 객체

class BaseDTO {
    validate(props) {
        if (!props) throw new Error("body 비어있음");
        if (typeof props !== "object")
            throw new Error("body 타입 올바르지않음");

        for (const key in props) {
            if (!props[key]) {
                throw new Error(`${key} 속성이 비어있음`);
            }
        }
    }

    todate(d) {
        const date = new Date(d);
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();

        return `${year}-${month}-${day}`;
    }
}

module.exports = BaseDTO;
const BaseDTO = require("../dto");

class UserCreateRequestDTO extends BaseDTO {
    userid;
    userpw;
    username;

    constructor(body) {
        super();
        this.userid = body.userid;
        this.username = body.username;
        this.userpw = body.userpw;
        this.validate(this);
    }
}

class UserCreateResponseDTO extends BaseDTO {
    userid;
    username;
    created_at;
    updated_at;

    constructor(response) {
        super();
        this.userid = response.id;
        this.username = response.name;
        this.created_at = this.todate(response.createdAt);
        this.updated_at = this.todate(response.updatedAt);
        this.validate(this);
    }
}

module.exports = {
    UserCreateRequestDTO,
    UserCreateResponseDTO,
};

 

 

 

4. create

 

- user.controller.js 에서 UserCreateRequestDTO 인스턴스 생성

   - UserCreateRequestDTO에는 req.body를 담아서

   - userService.createUser에 UserCreateRequestDTO을 호출하고 responseBody 에 할당

 

-  user.service.js에서 UserCreateResponseDTO 인스턴스 생성

   - createUser에 UserCreateRequestDTO에서 userid, userpw, username꺼내서

   - DB에 바로 INSERT하기전에  User.build() 메서드로 인스턴스를 생성해서 확인해본다음 save()

 

 

 


※ npm run start

 - node server라고 적어서 실행했던것을 package.json  srcript에서 "start": "node index" 를 적고 저장해두고 사용!

 

※  build 메서드

 - build 메서드는 데이터베이스에 저장하기 전에 모델의 인스턴스를 생성

 - build 메서드로 생성된 모델 인스턴스는 데이터베이스에 저장되지않는다!

   - 데이터의 미리보기를 얻을 때 유용하며, 필요한 경우 save 메서드를 호출하여 데이터베이스에 저장할수있다.

- 따라서 데이터베이스와 상호작용하기 전에 중간 단계로 활용한다!

 

 

※ 나머지도 작업해보기


   




'NodeJS' 카테고리의 다른 글

NodeJS - KAKAO LOGIN (추가)  (0) 2023.10.26
NodeJS - TDD  (0) 2023.10.25
NodeJS - ORM, Sequelize, User CRUD  (1) 2023.10.23
NodeJS - RESTful API, 회원가입 (Front, Back 분리)  (1) 2023.10.20
NodeJS - Server 분리 (Front, Back), CORS Error  (1) 2023.10.19