Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

官方文档里的swagger用法错误 #3019

Open
Tracked by #3756
dayueba opened this issue Jun 9, 2023 · 1 comment
Open
Tracked by #3756

官方文档里的swagger用法错误 #3019

dayueba opened this issue Jun 9, 2023 · 1 comment

Comments

@dayueba
Copy link

dayueba commented Jun 9, 2023

  • Node Version:
  • 20.2.0
  • Midway Version(Decorator/Core):
  • 3.3.0

https://midwayjs.org/docs/extensions/swagger#泛型返回数据

文档里是这么说的

export function SuccessWrapper<T extends Type>(ResourceCls: T) {
  class Successed {
    @ApiProperty({ description: '状态码' })
    code: number;

    @ApiProperty({ description: '消息' })
    message: string;

    @ApiProperty({
      type: ResourceCls,
    })
    data: T;
  }

  return Successed;
}

实际上 data 的类型要改为 data: InstanceType<T>; 才对

如果是 T 只能传类型,不能传实例

测试code

import { Type } from "@midwayjs/swagger";

export function SuccessWrapper<T extends Type>(ResourceCls: T) {
  return class {
    code: string;
    message: string;
    data: T; // 正确做法:通过 InstanceType<T> 获得 T 的实例类型
  };
}

export class SearchRespDto {
  product_list: string[]
}

export class SearchResp extends SuccessWrapper(SearchRespDto) {}

const searchRespData = new SearchRespDto();
const searchResp = new SearchResp(); 
searchResp.data = searchRespData; // 这里会赋值失败
@czy88840616
Copy link
Member

czy88840616 commented May 6, 2024

想了下,这里有点问题,这个 T 不应该限定是 class,因为做定义用,只需要参数和返回值做限定,比如

type Res<T> = {
      code: number;
      message: string;
      data: T;
    }

    function SuccessWrapper<T>(ResourceCls: Type<T>): Type<Res<T>> {
      class Result<T> implements Res<T> {
        @ApiProperty({ description: '状态码' })
        code: number;

        @ApiProperty({ description: '消息' })
        message: string;

        @ApiProperty({
          type: ResourceCls,
        })
        data: T;
      }

      return Result;
    }

    class User {
      @ApiProperty()
      name: string;

      @ApiProperty()
      id: number;
    }

    class SuccessUser extends SuccessWrapper<User>(User) {}

    @Controller('/api')
    class APIController {
      @Post('/update_user')
      @ApiCreatedResponse({ type: SuccessUser })
      async updateUser(@Body() data: SuccessUser) {
        const successUser = new SuccessUser();
        successUser.code = 200;
        successUser.message = 'Success';
        successUser.data = {
          name: 'Kitty',
          id: 1,
        };
        return successUser;
      }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants