0

我从这个答案https://stackoverflow.com/a/53385010/6578441中使用了 TransformInterceptor 。它工作得很好。

Bud如何将实体数组转换为dto?

控制器:

  @Get()
  @UseInterceptors(new TransformInterceptor(ArrayDto))
  get(
  ): MyEntity[] {
    return [
       new MyEntity(),
       new MyEntity(),
       new MyEntity(),
    ]

  }

ArrayDto:

@Exclude()
export class ArrayDto {
  @Expose()
  readonly items!: ItemDto[];
}

ItemDto:

@Exclude()
export class ItemDto {
  @Expose()
  readonly id!: string;
}

预期输出:

{
  items: [
    { id: '' },
    { id: '' },
    { id: '' },
  ]
}

实际输出:

[{},{},{}]

谢谢你的帮助

4

0 回答 0