Upgrading to Vapor 4: how to create a model and returning it

Viewed 436

In my old Vapor 3 code I'm creating models like this:

address.create(on: conn).flatMap { savedAddress in
    // do something with saved address
}

With the help of the Vapor 4 documentation I'm now passing db to the create function instead of a connection. The issue is, that it seems that flatMap returns Void as I'm getting the following error when I try to access savedAddress: "Value of tuple type 'Void' has no member ...".

How should I rewrite this?

1 Answers

Because all models in Fluent 4 must be classes, you can rely on reference semantics to do what you want (which is why create(on:) returns EventLoopFuture<Void>. So in your example, instead of savedAddress you can just use address as the saved model. When it has been saved, Fluent will set the ID property of your model on the address object, which you can then retrieve in your flatMap closure with address.requireID()

Related