본문 바로가기

Nodejs/NestJS

[NestJS]Swagger 설정 및 @UseInterceptors (ClassSerializerInterceptor) 적용하기 09

yarn add @nestjs/swagger @fastify/swagger @fastify/swagger-ui

 

  setSwaggerMiddleware(app);

function setSwaggerMiddleware(app: NestFastifyApplication) {
  const config = new DocumentBuilder()
    .setTitle("Nestjs Toy API DOCS")
    .setVersion("1.0")
    .addBearerAuth({ type: "http", scheme: "bearer", name: "JWT", in: "header" })
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup("/api", app, document, { swaggerOptions: { defaultModelsExpandDepth: -1 } });
}

 

 

  console.log(`http://localhost:${PORT}/api`);

 

 

swagger에서 return할 때, class-transformer , class-validator 적용하기 위해서  @UseInterceptors(ClassSerializerInterceptor) 적용 필요

@Entity()
export default class User extends BaseEntity {
  @PrimaryGeneratedColumn({ type: "bigint" })
  @ApiProperty()
  id: number;

  @Column()
  @ApiProperty()
  @IsString()
  name: string;

  @Column()
  @ApiProperty()
  @IsString()
  @Exclude()
  password: string;

  @OneToMany(() => UserConfig, (config) => config.user)
  config: UserConfig;
}

@Entity()
export default class UserConfig extends BaseEntity {
  @PrimaryGeneratedColumn({ type: "bigint" })
  @ApiProperty()
  id: number;

  @Column()
  user_id: number;

  @Column()
  @Exclude()
  is_ok: boolean;

  @ManyToOne(() => User, (u) => u.id)
  @JoinColumn({ name: "user_id" })
  @ApiProperty()
  @IsObject()
  user: User;
}

------------------

  @Get("/users")
  @UseInterceptors(ClassSerializerInterceptor)
  getUser() {
    const user = new User();
    user.id = 1;
    user.name = "name";
    user.password = "password";
    const config = new UserConfig();
    config.user_id = 1;
    config.is_ok = false;
    user.config = config;

    return [user];
  }
  
  -------------------------------
  result : [
    {
        "id": 1,
        "name": "name",
        "config": {
            "user_id": 1
        }
    }
]

exclude 적용한 user와 userconfig까지 적용되는 것 확인했음.

 

현재까지 코드 보기: https://github.com/close852/nestjs-toy/tree/09

 

반응형