I'm using the TypeScript library "Automapper" in my NestJS backend to convert an answer of MongoDb/Mongoose to an DTO. That's how the answer looks like:
{
"_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"]
}
]
}
My problem is, that I don't know how to convert the entries of the "widgets" array to different DTOs (ImageDTO, ConversationDTO) based on the "type" attribute/discriminator.
How can I solve that?
Currently I use the following:
mapper.createMap(MeetingSpace, MeetingSpaceDto).forMember(
(destination) => destination.widgets,
mapWith(WidgetDto, Widget, (source) => source.widgets)
);
But I have to find a way to map a "Widget" to an "ImageDto" or "ConversationDto" because of the "type".
mapWith(ImageDto, Widget, (source) => source.widgets)
mapWith(ConversationDto, Widget, (source) => source.widgets)
I know this is a bit late - but I just came across the same need.
You need to define the mapping from Widget to ImageDTO
createMap(mapper, Widget, ImageDTO);
Then use the map function on the collection:
return source.widgets.map(widget => mapper.map(widget, Widget, ImageDTO);