Skip to content

Commit

Permalink
fix: http 호스팅에서 swagger ui가 나오지 않는 문제 해결 (#10)
Browse files Browse the repository at this point in the history
[관련 git issues](scottie1984/swagger-ui-express#212 (comment))

- helmet 이 swagger ui보다 먼저 적용되는 경우 발생하는 에러로 적용 순서를 변경하여 해결하였다
  • Loading branch information
dbwogus94 committed Feb 20, 2024
1 parent 68ea5e9 commit cc1b31a
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 3 deletions.
18 changes: 18 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# PR Summery

## [FEATURE]

- ex) (공통 UI 제작)[notion 티켓 url 첨부]

## [WORK-LOG]

- 작업 진행 과정 설명
- ex) feature일 경우 feature 진행과정 설명

## [HOW-TO] (optional)

- ex) fix PR일 경우 픽스 설명

## [ISSUE] (optional)

- 관련 라이브러리 설치
30 changes: 27 additions & 3 deletions src/common/app/nest-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import * as Sentry from '@sentry/node';
import { json } from 'express';
import helmet from 'helmet';
import helmet, { HelmetOptions } from 'helmet';

import { CorsConfig, SentryConfig } from '@app/config';
import { httpLogger } from '@app/custom';
Expand All @@ -23,6 +23,20 @@ type BuildSwaggerType = typeof buildSwagger;
type SetMiddlewareOptions = { httpLogging?: boolean; globalPrefix?: string };
type SetSwaggerOptions = { docsPath: string };

/**
* TODO: nest의 경우 미들웨어 셋팅 순서가 swagger 빌드에 영향을 준다.
* - 이것을 해결하기 위해 NestBuilder#runServer()에서 미들웨어와 스웨거 빌드를 순차적으로 적용하게 수정하자.
* - ex)
* 1. set 메서드에 따라 배열에 담는다.
* 2. NestBuilder#runServer() 메서드에서 서버 실행 전 셋팅된 미들웨어를 순차로 적용시킨다.
* ```
* builder
* .setMiddleware({ globalPrefix: '/api', httpLogging: true })
* .setSwagger(buildSwagger, { docsPath: '/docs' })
* .setSecurity()
* .runServer();
* ```
*/
export class NestBuilder {
private _isRunning: boolean;

Expand Down Expand Up @@ -66,6 +80,18 @@ export class NestBuilder {
return this;
}

/**
* 보안 설정(helmet) 설정
* - swagger-ui를 http 배포환경에서 사용하려면 swagger ui 빌드 후에 선언되어야 한다.
* @param options
* @returns
* @see https://github.com/scottie1984/swagger-ui-express/issues/212#issuecomment-825803088
*/
setSecurity(options?: Readonly<HelmetOptions>) {
this._app.use(helmet(options));
return this;
}

/**
* Express middleware 셋팅
* @param options
Expand All @@ -83,14 +109,12 @@ export class NestBuilder {
if (!!options.globalPrefix) {
this._app.setGlobalPrefix(options.globalPrefix); // Note: Swagger 빌드전에 적용해야 docs에 적용된다.
}

const { origin, ...other } = this._configService.get<CorsConfig>('cors');
this._app.enableCors({
...other,
origin: typeof origin === 'string' ? origin.split(',') : origin,
});
this._app.use(json({ limit: '50mb' }));
this._app.use(helmet());
return this;
}

Expand Down
2 changes: 2 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@ async function bootstrap() {
return EnvUtil.isProd()
? await builder //
.setMiddleware({ globalPrefix: '/api', httpLogging: false })
.setSecurity()
.initSentry()
.runServer()
: await builder
.setMiddleware({ globalPrefix: '/api', httpLogging: true })
.setSwagger(buildSwagger, { docsPath: '/docs' })
.setSecurity()
.runServer();
}

Expand Down

0 comments on commit cc1b31a

Please sign in to comment.