typescript - 如何借助 Automapper (TypeScript) 映射充满不同 DTO 的数组条目?

标签 typescript mongodb nestjs automapper

我正在使用 TypeScript 库 "Automapper"在我的NestJS后端转换 MongoDb/Mongoose 的答案到 DTO。答案如下:

{
    "_id": "mongo-object-id",
    "widgets": [
      {
        "id": "UUID",
        "type": "IMAGE",
        "zIndex": "0",
        "position": { "x": 1, "y": 2 },
        "pinned": false,
        "height":500,
        "width":1000
      },
      {
        "id": "UUID",
        "type": "CONVERSATION",
        "zIndex": "1",
        "position": { "x": 3, "y": 7 },
        "pinned": false,
        "participants": ["UUID1","UUID2"]
      }
    ]
  }

我的问题是,我不知道如何根据“type”属性/鉴别器将“widgets”数组的条目转换为不同的 DTO(ImageDTO、ConversationDTO)。

我该如何解决这个问题?

目前我使用以下内容:

mapper.createMap(MeetingSpace, MeetingSpaceDto).forMember(
        (destination) => destination.widgets,
        mapWith(WidgetDto, Widget, (source) => source.widgets)
      );

但是由于“类型”,我必须找到一种方法将“Widget”映射到“ImageDto”或“ConversationDto”。

mapWith(ImageDto, Widget, (source) => source.widgets)
mapWith(ConversationDto, Widget, (source) => source.widgets)

最佳答案

我知道这有点晚了 - 但我刚刚遇到了同样的需求。

您需要定义从Widget到ImageDTO的映射

createMap(mapper, Widget, ImageDTO);

然后在集合上使用 map 函数:

return source.widgets.map(widget => mapper.map(widget, Widget, ImageDTO);

关于typescript - 如何借助 Automapper (TypeScript) 映射充满不同 DTO 的数组条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70535505/

相关文章:

file - 上传测试文件时如何修复 tsc-watch 重启?

javascript - 由于过滤器导致表达式更改而导致 *ngIf 的渲染延迟 - Angular

javascript - TS TypeScript SetInterval - 无法从计时器目标函数内部访问函数

Javascript 到 Mongodb 查询直通。安全的?不好的做法?

javascript - 使用 Gulp Data 在 Gulp 中获取来自 Mongo 的数据

javascript - 如何在 Mongoose 模型中定义方法?

jestjs - 嵌套 e2e 测试 : Jest did not exit one second after the test run has completed

angular - 带有 Angular 和 Nest 的 NX : package. json treeshaking

angular - 有没有办法修复 Angular CLI 生成的文件以停止在 WebStorm 中显示红色

ruby-on-rails - Angular 4 和 Rails 5 发布请求 JSON 格式化