7. Nest.js 광부왕 게임 서버 Interceptor 적용

2023. 3. 3. 17:13프로젝트/게임 서버 - Nest.js

1. src/common/interceptors/success.interceptor.ts 파일 생성

success.interceptor.ts 파일을 만들어 준다.

 

* 클라이언트에서는 API가 정상적으로 요청이 되었는지 result :true를 통해 확인 한다.

import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class SuccessInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const reg = new RegExp(/\/log\/\d{4}-\d{2}-\d{2}\/\d{4}-\d{2}-\d{2}/);
    if (reg.test(context.getArgs()[0].url)) {
      return next.handle();
    } else {
      return next.handle().pipe(
        map((data) => ({
          result: true,
          data,
        })),
      );
    }
  }
}

2. main.ts에 적용

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import expressBasicAuth from 'express-basic-auth';
import { AppModule } from './app.module';
import { ErrorExceptionFilter } from './common/filters/error.exception';
//추가
import { SuccessInterceptor } from './common/interceptors/success.interceptor';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new ErrorExceptionFilter());
  //추가
  app.useGlobalInterceptors(new SuccessInterceptor());  
  if (process.env.NODE_ENV === 'product') {
    app.use(
      ['/docs'],
      expressBasicAuth({
        challenge: true,
        users: { [process.env.SWAGGER_USER]: process.env.SWAGGER_PWD },
      }),
    );
  }

  const config = new DocumentBuilder()
    .addBearerAuth()
    .setTitle('광부왕')
    .setDescription('king-of-mine-worker-back Api')
    .setVersion(process.env.VERSION)
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('docs', app, document);
  await app.listen(process.env.PORT);
}
bootstrap();
728x90
반응형