API 문서를 만들어야 한다.
API를 만들면, FE 한테 설명을 해줘야 한다.
nest는 알아서 문서를 만들어 준다.
그 tool을 사용해 볼 것이다.
Fastify
참고사항 성능을 빠르게 하고 싶으면 Express 보다 빠른 Fastify를 사용하는 것도 좋다.
Swagger 사용
설치
npm install --save @nestjs/swagger
main.ts
import { SwaggerModule, DocumentBuilder, OpenAPIObject } from '@nestjs/swagger';
...
const config = new DocumentBuilder()
.setTitle('C.I.C')
.setDescription('cat')
.setVersion('1.0.0')
.addTag('cats')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs', app, document);
http://localhost:8000/docs
위로 접속해보면 (docs라는 url로 접근하면 된다.)
해당 문서들을 만들어 준다.

아쉬운 점은, 얘가 뭔지를 잘 모를 수 있다.
그래서 설명을 만들어주면 좋다.
controller로 가서
@ApiOperation({summary: '회원가입'})
@Post()
async signUp(@Body() body: CatRequestDto) {
return await this.catsService.signUp(body);
}
@ApiOperation({summary: ‘회원가입’})
를 사용하여 만들어주면 해당하는 설명을 쓸 수 있다.
테스트 데이터의 형식 지정
그리고 테스트 데이터를 넣어서 보내볼 수도 있는데
테스트 데이터의 형식은 dto 에 넣어서 설정할 수 있다.
import { ApiProperty } from '@nestjs/swagger/dist/decorators';
import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
export class CatRequestDto {
@ApiProperty({
example: 'dddd@naver.com',
description: 'email',
required: true,
})
@IsEmail()
@IsNotEmpty()
email: string;
@ApiProperty({
example: '123456',
description: 'password',
required: true,
})
@IsString()
@IsNotEmpty()
password: string;
@ApiProperty({
example: '이름이다',
description: 'name',
required: true,
})
@IsString()
@IsNotEmpty()
name: string;
}
이렇게 하면 된다.
Response 예시 적어주기
@ApiResponse({
status: 500,
description: 'Server Error...'
})
@ApiResponse({
status: 200,
description: '성공!',
type: ReadOnlyCatDto
})
@ApiOperation({summary: '회원가입'})
@Post()
async signUp(@Body() body: ReadOnlyCatDto) {
return await this.catsService.signUp(body);
}
위와 같음.
성공했을 때 type을 ReadOnlyCatDto를 사용해줬는데
cat.dto.ts 파일을 만들어서 아래와 같이 만들어준다.
import { ApiProperty } from '@nestjs/swagger';
import { Cat } from '../cats.schema';
export class ReadOnlyCatDto{
@ApiProperty({
example: '12345678',
description: 'id',
required: true,
})
id: string;
@ApiProperty({
example: 'dddd@naver.com',
description: 'email',
required: true,
})
email: string;
@ApiProperty({
example: '이름이다',
description: 'name',
required: true,
})
name: string;
}
Readonly 정보들만 모아서 보내주기 위함이다.
상속을 통해 여러 타입을 재사용성을 높이기
import { Cat } from '../cats.schema';
export class CatRequestDto extends Cat {}
위와 같이 extends 를 쓰면 된다.
export class ReadOnlyCatDto extends PickType(Cat, ['email', 'name'] as const){
@ApiProperty({
example: '12345678',
description: 'id',
required: true,
})
id: string;
}
ReadOnly에선 password를 보면 안되므로 PickType이란 거를 써서 가져오고 싶은애만 가져온다.
OmmitType은 빼고 싶은애를 빼는 것임.
CORS
Cross Origin Resource Sharing
내가 설정해주지 않은 애가 접근 방지
backend 에서 이거 허용하는 설정을 해주어야 한다.
app.enableCors({
origin: true,
credentials: true
})
main에 위 코드를 추가한다.
origin 에서는 보통 허용하는 링크를 거는 것이 일반적이지만 true로 하면 모든 링크에 대한 허용이 된다.
또 credential은 여기서도 설정하지만 frontend에서도 설정해주어야 한다.