@nestjs/swagger 插件中的 NestJS typeorm 分页类型

编程入门 行业动态 更新时间:2024-10-09 15:19:29

@nestjs/swagger 插件中的 NestJS typeorm <a href=https://www.elefans.com/category/jswz/34/1769545.html style=分页类型"/>

@nestjs/swagger 插件中的 NestJS typeorm 分页类型

我有一个端点,它返回一个带有分页的列表。 我正在尝试使用 nestjs/swagger 插件自动收集端点和 DTO 等。 插件适用于所有端点,但返回类型为 typeorm 分页的端点除外。

  findAll(
    @Query('page', new DefaultValuePipe(1), ParseIntPipe) page : number,
    @Query('limit', new DefaultValuePipe(10), ParseIntPipe) limit : number,
    @Query('domain') domain: string,
  ): Promise<Pagination<webContent>> {
    return this.webService.findAll({ page, limit }, domain);
  }

网页内容是:

export default class webContent {
  @PrimaryColumn()
  domain: string;

  @ManyToMany(() => WebCategory)
  @JoinTable()
  categories: WebCategory[];
}

任何解决方案?

回答如下:

玩这个,例如你可以添加一个构造函数来映射属性:

import { Type, applyDecorators } from '@nestjs/common';
import { ApiExtraModels, ApiOkResponse, ApiProperty, getSchemaPath } from '@nestjs/swagger';

import { PaginationResponseDto } from '@shared';

export class PaginationModel<T> implements PaginationResponseDto<T> {
    @ApiProperty({ isArray: true })
    public readonly data: T[];

    @ApiProperty({ example: 1 })
    public readonly total: number;

    @ApiProperty({ example: 1 })
    public readonly page: number;

    @ApiProperty({ example: 1 })
    public readonly pages: number;
}

还有一个控制器装饰器:

export const ApiPaginatedResponse = <TModel extends Type<any>>(model: TModel) => {
    return applyDecorators(
        ApiExtraModels(PaginationModel),
        ApiOkResponse({
            description: 'Successfully received model list',
            schema: {
                allOf: [
                    { $ref: getSchemaPath(PaginationModel) },
                    {
                        properties: {
                            data: {
                                type: 'array',
                                items: { $ref: getSchemaPath(model) },
                            },
                        },
                    },
                ],
            },
        })
    );
};

用法示例:

@Get()
@ApiOperation({ summary: 'find paginated users' })
@ApiPaginatedResponse(UserModel)
// public async findUsers(...otherLogic

更多推荐

@nestjs/swagger 插件中的 NestJS typeorm 分页类型

本文发布于:2024-05-13 15:41:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1759908.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分页   插件   类型   nestjs   swagger

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!