Nest js 독학 삽질 일기 Day 3: Entity & DTO 파일 생성, config 이용해서 DB 보안 설정하기 , CREATE 구현 & 에러 핸들링

Dorito·2022년 9월 16일
1

NestJS

목록 보기
3/10

주의: 삽질 일기... 실시간으로 쓰면서 하기때문에 매우 의식의 흐름입니다.

CRUD

아니 내가 보면서 따라하려는 이 문서 에는 인터페이스 써서 혹시나 해서 뒤벼보니

DTO는 interface 또는 class로 선언이 가능합니다. 하지만 대게 class가 더 좋다고 한다.
왜냐하면? class는 JavaScript ES6 표준의 일부이므로 컴파일된 JavaScript에서 실제 Entity로 유지가 됩니다.
하지만, TypeScript Interface는 트랜스파일(!= 컴파일) 도중에 제거가 되므로 Nest가 런타임에서 참조할 수 없습니다!
TypeScript interfaces are removed during the transpilation, Nest can't refer to them at runtime.
따라서, 클래스로 DTO를 만들면 파이프와 같은 기능을 런타임에서 사용할 수 있기 때문에, class로 만들자.
출처

라고 한다.
뭐 제대로 되는게 없어 왜 .. . . . . .
저 문서는 그냥 순서를 어떻게 접근하나만 보고 깡으로 내가 다 해야겠다 .. (오히려 좋아)

이리저리 구글링해보니.. repository 디자인 패턴이란게 있다.
이걸로 CRUD를 해봐야지!!!
(보일러플레이트 코드 있긴 한데, 가오가 있으므로 직접 짜보겠다. 내가 능력이 없지!! 가오가 없나!!! )

공식문서에서 원하는 정보를 바로 못뽑아먹고 돌아돌아서 보게 되는듯
_구글링 -> 이런게 있구나 -> 오 이걸로 하면 되겠는데? -> 안되네.. -> 구글링

이 순서 무한 반복인듯. 비효율 끝판왕..
(쪽팔려서 안적으려했는데 오늘 중요한 파일 실수로 날려서... 깃허브 다시 클로닝해서 처음부터 시작했다..ㅋ)

아무튼

그러나

하.. typeORM 버전업이 너무 빨리되어서.. 블로그마다 말이 중구난방이다. 영어든, 한글이든... 그냥 공식문서를 찾아봐야겠다
https://typeorm.io/ 이게 공식문서임 이거 위주로 보고
https://orkhan.gitbook.io/typeorm/docs 이건 뭔지 모르겟는데 더 설명해주는 그런 문서인건가?

Repository Design Pattern

Repository is just like EntityManager but its operations are limited to a concrete entity. You can access the repository via EntityManager.

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './domain/User';
import { Repository } from 'typeorm/index';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private userRepository: Repository<User>,
  ) {
    this.userRepository = userRepository;
  }

InjectRepository 데코레이터를 통해 User Entity 를 userRepository 를 UserService 에 주입하여 사용하는 모습이다. 이것이 가능했던 준비의 과정들은 이전에 Entity를 만들고 AppModule 에 TypeOrm 다이내믹 모듈을 통해 커넥션 정보와 Entities 에 User 를 등록하고 사용하는 UserModule 에서 User Entity를 TypeOrm 다이내믹 모듈의 forFeature 를 통해 등록하였다. 이 과정이 Setup이 되어야만 위의 Repository 로 의존성 주입이 가능하고 해당 Repository를 통해 CRUD 를 할 수 있다.
출처

출처

오키 엔티티를 주물딱거리는 친구로구나

공식문서를 뒤벼보니
그중에서 그냥 Repository가 아니라 Custom Repository라는 것이 있다.
더 간지나보임
저거 써보고싶다 (가오가 될 것인지 과오가 될 것인지는 미래의 내가 알아서 하겠지)

https://typeorm.io/custom-repository 보고있는데ㅔ.. 어떻게 해야할지 감이 안온다 심지어

typeORM 0.3 버전부터 EntityRepository is deprecated 라고 한다...
(https://kyungyeon.dev/posts/83 여기에 0.3으로 올라가면서 바뀐 부분 친절히 잘 설명되어있다.)

오케이

휴 그래서 @EntityRepository는 어떻게 쓰는거지
-> https://gist.github.com/anchan828/9e569f076e7bc18daf21c652f7c3d012

막막하다..

일단 custom repository는 이따가 하는 걸로 하자.

아무튼 MySQL과 nestJS를 typeORM 연결하는건
https://www.makeuseof.com/nestjs-typeorm-sql-databases/
여기를 참고했다.

  • Injecting Your Repository to Its Service Using Dependency Injection
    Dependency injection is a software engineering technique that is a form of the inversion of control principle. It shifts the burden of dependency management from client code to the library or service it depends upon.

Follow the steps below to inject your repository into a service:

  1. In your service file, import Repository from typeorm and the InjectRepository decorator from @nestjs/typeorm. Also import the entity you want to inject its repository.
  2. In your service class, create a constructor.
  3. Declare a private variable, repo, as a parameter in the constructor to initialize it.
  4. Assign a type of Repository to repo with a generic type of your entity.
  5. Annotate repo with the InjectRepository decorator and pass your entity as an argument.

Repository DI

이런식으로 코드 참고해서 짜면 됨..

// test.service.ts
import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Test } from './test.entity';
 
@Injectable()
export class TestService {
  constructor(
    @InjectRepository(Test)
    private repo: Repository<Test>,
  ) {}
}

Create 구현

최근 업로드된 유투브 영상까지도 찾아보고
거기에서 코드나 방식들을 참고해야겠다는 생각이 들었음.

https://youtube.com/watch?v=woMPn3Nm3aA&feature=share&utm_source=EKLEiJECCKjOmKnC5IiRIQ

오케이 여기 영상이랑

https://github.com/sramocki/nestjs-typeorm-example-migrations/tree/master/src/car 여기 깃허브 보면서 대충 틀이 어떻게 되어있는지 공부해봐야겠따.

DTO 세팅

dto created_at typeorm example 이라 구글링하니까
https://khalilstemmler.com/articles/typescript-domain-driven-design/repository-dto-mapper/

여기 문서 유용해보임. 읽어보니 엄청 기초 개념부터 차근차근 알려줘서 좋다. (MVC모델이란 ~ 부터 )


https://www.linkedin.com/pulse/nestjs-request-data-validation-nestor-iv%C3%A1n-scoles

Entity 수정함

  • uuid, created_at은 어떻게 json으로 보내지..?ㅋ -> 엔티티를 다시 재설정해야할듯

https://stackoverflow.com/questions/72315983/how-to-match-date-timestamp-field-as-a-text-in-typeorm-query-builder

uuid https://prairielearn.readthedocs.io/en/latest/uuid/
https://www.angularfix.com/2022/01/how-to-select-uuid-version-in-entity.html

TypeORM uses RFC4122 compliant UUID v4 function for drivers which do not have a built-in uuid function

이렇게 해봤는데 잘 안됐다

더 찾아보니 공식문서에 뻔히 나와있었구나...

결국은 이 코드 보고 시도해봤다!!!

  • uuid Entity, time stamp 엔티티 구현 성공~!
    전체 엔티티 코드
import {
  Binary,
  Column,
  CreateDateColumn,
  Entity,
  Generated,
  PrimaryColumn,
  PrimaryGeneratedColumn,
} from 'typeorm';

@Entity()
export class Board {
  // @PrimaryColumn({ type: 'binary', length: 16 })
  // id!: Buffer; 에서 바꿈
  
  @PrimaryColumn({ type: 'binary' })
  @Generated('uuid')
  id: string;

  @Column()
  title: string;

  @Column()
  description: string;

  @Column()
  body: string;

  @Column()
  author: string;

  // @CreateDateColumn({ type: 'timestamp' })
  // date_posted: Date;

  @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
  dated_at?: Date;
}

솔찍히 어디 책에 잘 나와있을듯.. 혼자서 찾아보니까 비효율적인거같다 , , ㅠ

Create 성공...

근데 customRepository를 쓰지는 못했다.
나중에 일단 CRUD 완성하고 나서 바꿔봐야지

Git 올릴 때 오류..

github 푸시하니까 깃허브 아이디 비번을 요구해서 이상하다 싶어서 구글링함

why git push Username for 'https://github.com': 이라고 구글링해서 오류 해결함


깃허브 목표

  1. 커밋 잘게 쪼개기. (커밋 가능한 한 30줄 이상 안넘게.. )
  2. 커밋할 때 오류없이 돌아가는 것 보고 하기
  3. 하나의 태스크는 하나 이상의 브랜치가 되어야함 (CRUD 브랜치 4개 만들어보기)
  4. 브랜치 따고 태스크 별로 코드 짜는 연습하기
  5. prefix {fix (에러 관리), feat(기능 추가), comment(주석 추가), chore (버전관리) }

Entity, DTO 수정, CREATE 구현 최종 코드

Entity, DTO 수정 & Create 구현 github

Create 에러 핸들링 최종 코드

feat: Create error handling github


DB 보안 설정 (내일 하기)

https://docs.nestjs.com/techniques/configuration

.Env 써서 보안 설정하기도 하는데... 어차피 언젠간 둘 다 쓰겠지 싶어서
config가 더 간지나서 해야지
했는데 시간이 너무 늦어서.. 내일 해야지

0개의 댓글