Project/NYAM
NestJs Swagger Header 추가
sung.hyun.1204
2023. 1. 2. 17:07
NestJs Swagger add Header
NestJs Swagger add prefix url path
가정 : swagger 설치 후
상황 :
2개의 Custom Header
x-token : accessToken - JWT
x-type : "admin" ,"owner", "user"
main.ts file 에
.addApiKey(
{
type: 'apiKey',
name: 'x-token',
in: 'header',
description: 'Enter token',
},
'x-token',
)
을 추가해준다.
code
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './common/exceptions/http-exception.filter';
import { SuccessInterceptor } from './common/interceptors/success.interceptor';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
const configService = app.get(ConfigService);
const port = configService.get('server.port');
app.enableCors({
origin: true,
credentials: true,
});
app.useStaticAssets(join(__dirname, '..', 'client'), {
prefix: '/api/v1/client',
});
app.useGlobalInterceptors(new SuccessInterceptor());
app.useGlobalFilters(new HttpExceptionFilter());
app.setGlobalPrefix('api/v1');
const swagger_options = new DocumentBuilder()
.setTitle('Docs')
.setDescription('API description')
.setVersion('1.1.0')
.addApiKey(
{
type: 'apiKey',
name: 'x-token',
in: 'header',
description: 'Enter token',
},
'x-token',
)
.addApiKey(
{
type: 'apiKey',
name: 'x-type',
in: 'header',
description: 'Enter type',
},
'x-type',
)
.build();
const document = SwaggerModule.createDocument(app, swagger_options);
SwaggerModule.setup('api-docs', app, document);
await app.listen(port, '0.0.0.0');
console.log('Application Listening on Port : ', port);
}
bootstrap();
기존 :@UseGuards 2개가 걸려있다. Authguard : jwt token check , RolesGuard : Role check
@Get('/list')
@ApiSecurity('x-token')
@ApiSecurity('x-type')
@UseGuards(AuthGuard, RolesGuard)
@Roles(Role.ADMIN)
async user_list_admin() {
const list = await this.userService.UserList();
const user_list = await Promise.all(
list.map((e) => this.userService.user_mange_data(e)),
);
return { user_list: user_list };
}
----------------------------------------------------------------------------------------------------------------------
서버 실행후
주소 :
http://localhost:3003/api-docs 로 접속한다.
header 에 postman 에서 넘겨 준 것 과 같은 정보를 넘겨준다
확인