我和Nest + Swagger有个问题。当我打开我的装腔作势的文档时,我看到了我希望看到的所有端点,但有两个问题:
No parameters,尽管为身体定义了DTO最终,我认为问题是:Swagger + Nest并不是为每个方法创建唯一的**。我的理解是,只有当方法不够独特时,它们才能获得唯一的operationId:例如,有两个具有相同调用签名的方法。
在过去,当我遇到这样的问题时,要么是因为我错过了@ApiTags装饰器,要么是我意外地包含了重复的端点。
一般来说,我觉得我在配置Swagger时错过了一个步骤,或者我没有正确地用Fastify设置它。我安装了fastify-swagger,但实际上我没有在任何地方使用它,但是根据Nest网站上的文档,在使用Fastify时,摆在嘴边的JSON的路由应该是/api/json,这是给我的。
那些不起作用的事情:
@ApiOperation注释方法addTag链中添加DocumentBuilderswagger-ui-express和@nestjs/platform-express依赖项更新:
将@ApiOperation({ operationId: 'test' })添加到方法中确实解决了这一问题,但我的印象是,@nest/swagger是自动这样做的。我的方法还不够独特吗?
main.ts
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}),
);
app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector))); // allows automatic serialization
app.enableCors();
const config = new DocumentBuilder().setTitle('PIM API').build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs', app, document);
await app.listen(process.env.APP_PORT || 3001);
}
bootstrap();某些控制器
@ApiTags('chat-messages')
@Controller('chat-messages')
export class ChatMessagesController {
constructor(
private readonly service: ChatMessagesService,
) {}
@Post()
create(@Body() createChatMessageDto: CreateChatMessageDto) {
return this.service.create(createChatMessageDto);
}
@Get(':stream_id')
findByStreamId(@Param('stream_id') streamId: string) {
return this.service.findByStreamId(streamId);
}ChatMessageDto
export class CreateChatMessageDto {
constructor(partial: Partial<CreateChatMessageDto>) {
Object.assign(this, partial);
}
@IsString()
value: string;
@IsRFC3339()
timestamp: Date;
@IsNotEmpty()
streamId: string;
}Swagger JSON
{
"/chat-messages":{
"post":{
"operationId":"ChatMessagesController_",
"parameters":[
],
"responses":{
"201":{
"description":"",
"content":{
"application/json":{
"schema":{
"$ref":"#/components/schemas/ChatMessage"
}
}
}
}
},
"tags":[
"chat-messages"
]
}
},
"/chat-messages/{stream_id}":{
"get":{
"operationId":"ChatMessagesController_",
"parameters":[
],
"responses":{
"200":{
"description":"",
"content":{
"application/json":{
"schema":{
"type":"array",
"items":{
"$ref":"#/components/schemas/ChatMessage"
}
}
}
}
}
},
"tags":[
"chat-messages"
]
}
}
}发布于 2022-01-27 13:25:41
你试过把@ApiProperty放在你的dto里吗?
如下所示:
export class CreateChatMessageDto {
constructor(partial: Partial<CreateChatMessageDto>) {
Object.assign(this, partial);
}
@ApiProperty()
@IsString()
value: string;
@ApiProperty()
@IsRFC3339()
timestamp: Date;
@ApiProperty()
@IsNotEmpty()
streamId: string;
}这允许Swagger查看属性。这是NestJ在他们的文档看这里中推荐的
https://stackoverflow.com/questions/70765024
复制相似问题