혼자 고민해보기_ 개발

nest js

nuri-story 2023. 8. 6. 17:35

 

https://www.youtube.com/watch?v=3JminDpCJNE&list=PL9a7QRYt5fqmxPccmnDTUXWeyKm4h2lHl

설치

npm i -g @nestjs/cli

실행

 npm run start:dev

파일 생성하고 터미널에서 진입한 뒤 생성 -npm: 기본 포맷이 다 설정된 상태로 파일이 열림

nest new ./

 

완전체 생성

파일명에 users 나 shows 같이 넣으면 됨

nest g resource 파일명

 

 

module생성

아무것도 없지만 모듈이 자동으로 생기게 하는 것

nest g module boards

controller생성

--no--spec 넣어서 테스트 생성은 막는다.

명령어로 생성하면 module.ts와 자동으로 연결해준다

nest g controller boards --no-spec

service 생성

module부분에 자동으로 연결

nest g service boards --no-spec

Dto
Data Transfer Object의 약자로 데이터를 우리가 사용할수있게 오브젝트로 바꿔주는거
데이터 유효성을 체크하는데 효율적, 더 안정적인 코드 작성

PIPE

유효성 체크하기

class-validator, class-transformer 모듈 설치가 필요함

npm install class-validator class-transformer --save

create-board.dto.ts

import { IsNotEmpty } from 'class-validator';

export class CreateBoardDto {
  @IsNotEmpty()
  title: string;

  @IsNotEmpty()
  description: string;
}

nest.js에서 이미 만들어진 파이프 활용할 수 있음

validationPipe

parselntPipe

ParseBoolPipe

ParseArrayPipe

ParseUUIDPipe

DefaultValuePipe

NotFoundException 이것도 nest 기본 기능

    if (!found) {
      throw new NotFoundException();
    }

반환 메세지를 적고싶다면 이렇게

    if (!found) {
      throw new NotFoundException(`Can't find Board whit id ${id}`);
    }

PipeTransform
모든 파이프에서 구현해줘야하는 인터페이스

Type ORM
데이터베이스 연결하기
3가지 모듈 다운로드
@nestjs/typeorm : nestjs에서 typeorm을 사용하기 위해 연동해주는 모듈
typeorm : 타입오알엠 모듈
pg : Postgres

@npm install pg typeorm @nestjs/typeorm --save

Entity

 

 

인증기능 구현 준비

//auth 모듈 생성
nest g module auth

//auth 컨트롤러 생성
nest g controller auth --no-spec

//auth 서비스 생성
nest g service auth --no-spec

 

 

비밀번호 암호화하기

npm install bcryptjs --save

 

 

jwt (인증)

nestjs/jwt
// nestjs에서 jwt사용

nestjs/passport
// nestjs에서 passport사용

passport
//passport 모듈

passport-jwt
// jwt 모듈

타입스크립트 jwt 생성

npm install @types/passport-jwt --save

 

설정

npm install config --save