배꼽파지 않도록 잘 개발해요

[NestJS] Express의 Request 타입을 전역적으로 사용하는 방법 본문

BackEnd/Express / NestJS

[NestJS] Express의 Request 타입을 전역적으로 사용하는 방법

꼽파 2024. 8. 26. 13:40

https://programming-bellybutton.tistory.com/200

 

[NestJS] res.cookie를 사용하기 위해 Express의 Response를 import 해야함

프로젝트 리팩토링을 하고 있는데, Access token은 리스폰스의 리턴값으로 보내주고, Refresh token은 쿠키에 담아서 전송하기로 하였다. res.cookie를 사용하기 위해 Express의 Response를 importNest

programming-bellybutton.tistory.com

지난번에 이런 글을 쓴 적이 있다.

글의 요지는 NestJS에서 특정 속성(예: cookie)을 사용하기 위해 express의 객체를 불러와야 한다는 것이었다.

 

이번 프로젝트에서도 express의 Request 객체를 불러와야 하는 상황이 발생하였다.

 

@nestjs/common에서 제공하는 Request를 불러오면 request.socket 속성을 사용할 수 없다.

그렇다면 이런식으로 express에서 직접 Request 객체를 import 해서 쓰면 된다.

 

import { Request as ExpressRequest } from 'express';

혹은 줄여서

import { Request as ExpReq } from 'express';

 

https://stackoverflow.com/questions/76716047/how-do-i-amend-the-express-request-interface-without-using-namespace-in-type

 

How Do I Amend The Express "Request" Interface Without Using "namespace" In TypeScript?

I'm working on creating a "CurrentUserMiddleware" within NestJS that I can implement globally. I'm using Express (not Fastify) in my implementation of NestJS. I'm trying to update / amend...

stackoverflow.com

 

하지만 이렇게 되면 매번 이런식으로 import를 수동으로 해줘야 하므로 번거롭다.

그냥 프로젝트 폴더 전역에서 import { Request } from 'express'가 되면 좋을 것 같다.


NestJS 프로젝트 폴더 전역에서 express 객체 import 설정

https://stackoverflow.com/questions/76389584/how-can-i-use-global-declared-object-in-nestjs

 

How can I use global declared object in Nestjs?

// src/types/format.ts const ImageFormat = { JPG: 'jpg', JPEG: 'jpeg', PNG: 'png', GIF: 'gif', BMP: 'bmp', } as const; type ImageFormat = typeof ImageFormat[keyof typeof ImageFormat]; I ...

stackoverflow.com

https://stackoverflow.com/questions/76389584/how-can-i-use-global-declared-object-in-nestjs

 

How can I use global declared object in Nestjs?

// src/types/format.ts const ImageFormat = { JPG: 'jpg', JPEG: 'jpeg', PNG: 'png', GIF: 'gif', BMP: 'bmp', } as const; type ImageFormat = typeof ImageFormat[keyof typeof ImageFormat]; I ...

stackoverflow.com

 

실행방법은 다음과 같다.

1. src/types 폴더를 생성하여 express.d.ts 파일을 만든다.

이때 d는 declaration의 줄임말이다.

import { Request } from 'express';

declare global {
  namespace Express {
    interface Request {}
  }
}

  • import { Request } from 'express'; : express의 리퀘스트 객체를 가져온다. 이때 구조분해 할당을 하는 이유는 express.Request 대신 Request로 사용하기 위함이다.
  • declare global {} : 타입 선언을 전역 네임스페이스에 추가한다.
  • namespace Express {} : express 타입 정의가 포함된 곳에서 express 관련 타입을 정의한다.
  • interface Request {} : Express.Request 를 수정할 때 사용한다. 본인은 아무 속성도 추가하지 않았다. 

 

2. tsconfig.json에 다음 내용을 추가한다.

  "include": [
    "src/**/*",
    "src/types/*"
  ]

  • src/**/* : src 폴더 안에 있는 모든 .ts 파일을 컴파일
  • src/types/* : src의 types 안에 있는 모든 .ts 파일을 컴파일

 

2. tsconfig.json에 다음 내용을 추가한다.

  • import { Request } from 'express'; : express의 리퀘스트 객체를 가져온다. 이때 구조분해 할당을 하는 이유는 express.Request 대신 Request로 사용하기 위함이다.
  • declare global {} : 타입 선언을 전역 네임스페이스에 추가한다.
  • namespace Express {} : express 타입 정의가 포함된 곳에서 express 관련 타입을 정의한다.
  • interface Request {} : Express.Request 를 수정할 때 사용한다. 본인은 아무 속성도 추가하지 않았다. 

 

3. express가 제대로 import되는지 확인한다.

이러면 문제가 해결된다. 이제 번거롭게 매번 express를 import를 하지 않아도 된다.

728x90