Nest Swagger 4. 재 사용성 높히기

2022. 4. 21. 14:13Nest.js

Property 예시 값 생성 : 

https://crispypotato.tistory.com/199
Responese 예시 값 생성 : 

https://crispypotato.tistory.com/201

 

사용 이유 : 

두 개의 Swagger 기능을 만들면 

예시 값이 중복되는 코드가 생긴다. 

그 때 schame(model)에 property 값을 넣어 중복되는 코드를 제거 할 수 있다.

 

사용 방법 : 

test.model.ts 파일에서 import 하여 DTO 파일에서  ApiProperty를 작성 한 것과 같이

작성해 준다.

 

import { ApiProperty } from '@nestjs/swagger';

 

///test.model.ts

import { Prop, Schema, SchemaFactory, SchemaOptions } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { IsString, IsNotEmpty } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

const options: SchemaOptions = {
  timestamps: true,
  collection: 'test',
};

@Schema(options)
export class Test extends Document {
  @Prop({
    required: true,
    unique: true,
  })
  @ApiProperty({
    example: 'testid',
    description: 'id',
    required: true,
  })
  id: string;

  @Prop({
    required: true,
  })
  @IsString()
  @IsNotEmpty()
  @ApiProperty({
    example: 'sdfgdfg11',
    description: 'pwd',
    required: true,
  })
  pwd: string;

  @Prop({
    required: true,
    unique: true,
  })
  @ApiProperty({
    example: '010155554444',
    description: 'hp',
    required: true,
  })
  @IsString()
  @IsNotEmpty()
  hp: string;
}

export const TestSchema = SchemaFactory.createForClass(Test);

Schema(model)에 ApiProperty를 작성 한 후 DTO 파일에서 필요한 속성만 뺴서 사용하면된다.

 

 

 

///user.dto.ts

 

사용 방법 :

' id '와 ' hp ' 속성이 필요 한다면 PickType를 사용해서 뺴서 사용하면 된다. 

 

변경 전 

변경 전

변경 후

// 변경 후
import { PickType } from '@nestjs/swagger';
import { Test } from '../model/test.model';

export class FindUserCheckDto extends PickType(Test, [
  'id',
  'hp',
] as const) {}

코드가 확 줄어드는 것을 발견 할 수 있다 

response값과, request값도 일일이 적어 준다고 상상하면 엄청 큰 효율 이라고 볼 수 있다.

 

728x90
반응형