Node.js 6

[NestJs] Custom Decorator

나만의 데코레이터 만들어보기 export const User = createParamDecorator((data, context: ExecutionContext) => { const req = context.switchToHttp().getRequest(); const user = req.user as UsersModel; return user; }); User는 데코레이터의 이름이 된다. createParamDecorator 함수를 사용한다. 첫 번째 인자 data는 데코레이터의 인자값을 받아올 수 있다. (아래에서 id를 가져올 수 있다.) 4. 두 번째 인자 context는 ExcutionContext 타입이다. 이것을 활용해 요청 객체를 받아올 수 있다.

Node.js 2023.12.28

[NestJs]Guard 사용하기

Guard란?? pipe보다 먼저 실행된다. request 객체를 가지고 여러 가지 처리를 가능하게 한다. 대표적으로 인증 처리를 한다. 공식문서에 따르면 미들웨어보다 나은 방식으로 처리할 수 있다고 한다. 미들웨어는 next()로 어떤 라우터가 실행될지 모르지만 guard는 ExcutionContext를 사용하기 때문에 어떠한 라우터가 실행될지 명확히 알 수 있다. 코드가 명확해지고 DRY 하고 선언적으로 작성할 수 있다. Guard 사용법 1. Guard로 사용할 class를 선언한다. CanActivate 인터페이스를 구현해야 한다. @Injectable() export class BearerTokenGuard implements CanActivate { async canActivate(contex..

Node.js 2023.12.27

[NestJs]Pipe사용하기

Pipe란???? 다음은 NestJs에서 요청과 응답의 흐름을 나타낸다. controller전에 4번을 보면 pipes라고 있는 것을 확인할 수 있다. 파이프(pipe)란?? 엔드포인트에 도달하기 전 요청 데이터에 대해 유효성 검증을 할 수 있다. 요청 데이터에 대해 변환 작업을 할 수 있다. @Get(':id') getPost(@Param('id') id: string) { return this.postsService.getPostById(+id); } 다음과 같이 id를 통해 게시글을 조회하는 로직이 있다. 현재는 url에서 string으로 id를 받기 때문에 +를 이용하여 number타입으로 형변환을 해주었다. 우리는 서버에서 id는 항상 number를 사용할 것이기 때문에 넘어올 때부터 numbe..

Node.js 2023.12.26

[NestJs]Model간 Relationship 설정 + Relation Options

OneToOne 테이블 간 1:1 관계일 때 사용한다. 이 예시에선 유저와 유저 프로필에 대한 예제를 이용하겠다. // User Entity @OneToOne(() => ProfileModel, (profile) => profile.user) profile: ProfileModel // ProfileEntity @OneToOne(() => UserModel, (user) => user.profile) @JoinColumn() author: UserModel UserModel에서 ProfileModel 타입의 profile을 만든다. @OneToOne() 어노테이션을 적어준다. 첫 번째 인자는 콜백함수 형태로 ProfileModel을 받아준다. 두 번째 인자는 콜백함수 형태로 해당 profile의 user..

Node.js 2023.12.22

[NestJs] NestJs에서 typeorm 세팅하기(Docker-compose사용)

1.Nest 프로젝트 생성 // nest cli가 설치가 안되어있다면 설치해주어야 한다. npm i -g @nestjs/cli // 프로젝트 생성 nest new "프로젝트 이름" 2. 필요한 패키지 다운로드 (typeorm, postgres) yarn add @nestjs/typeorm typeorm pg 3.docker-compose 파일을 생성 후 파일 작성 데이터베이스 환경을 설치하기 위해서(여기서는 postgres를 사용한다.) yaml파일로 생성한다 // 사용할 서비스의 목록 services: //서비스 이름 postgres: // 이미지 이름 (docker hub) image: postgres:15 restart: always // 동기화 volumes: - ./postgres-data:/v..

Node.js 2023.12.18

[NestJs]의존성 주입과 제어의 역전

nest프레임워크를 공부하다가 보니 의존성 주입과 제어의 역전에 대하여 알게 되었다. 스프링을 공부할 때도 같은 개념이 사용되어 비교적 수월하게 이해하였다. nest의 핵심 이론인 만큼 한 번 더 정리해두려고 한다. 의존성 주입이란???? class A { } const a = new A(); 우리가 일반적으로 class를 생성하고 그 클래스를 바탕으로 인스턴스를 생성하는 과정이다.하지만 다음 코드를 보자. nest의 controller이다. @Controller('posts') export class PostsController { constructor(private readonly postsService: PostsService) {} } 컨트롤러에서 우리는 postsService를 자유자재로 사용할..

Node.js 2023.12.11
728x90