我正在使用 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/