#How to Create a DTO for a Model with Relationships and Convert it Back to a Model in Vapor?

1 messages · Page 1 of 1 (latest)

sacred ether
#

ProductDTO

struct ProductDTO: Content {
    var id: UUID?
    var name: String
    var code: String
    var isFinished: Bool
    var orderID: Order.IDValue
    var deliveryStatus: Delivery.Status?
    var statusHistory: [StatusHistoryDTO]
    
    public func toModel() -> Product {
        let model = Product()
        
        model.id = id
        model.name = name
        model.code = code
        model.isFinished = isFinished
        model.$order.id = orderID
        model.deliveryStatus = deliveryStatus
        model.statusHistory = statusHistory.map { $0.toModel() }
        
        return model
    }
}

Questions:

1 - Is this structure correct for working with DTOs and Model in Vapor, especially when it comes to handling relationships (like Parent and Children)?
2 - Is there a better way to convert between DTO and Model in a scenario with these kinds of relationships?
3 - Where can I find a more complex example or documentation that demonstrates handling DTOs and converting them back to models in Vapor, particularly with relationships like Parent and Children?

glad trellis
#

Relationships and DTOs get into "no right answer" territory, but you probably want to do model.$statusHistory.value = ... for the eager loading later on. Note that they won't get saved etc when you save the model