I'm confused on how to query the children of a model object and use it immediately. My Client
contains a number of Station
children
final class Client: PostgreSQLModel {
var stations: Children<Client, Station> {
return children(\.clientID)
}
}
and then in my controller I have a list of clients that I want to look at and grab their stations.
func clientIndexHandler(_ req: Request) throws -> Future<View> {
return Client.query(on: req).all().flatMap(to: View.self) { clients in
let sorted = clients.sorted { ... }
let content = try sorted.map { client in
let stations = try client.stations
.query(on: req)
.all()
.map(to: [String].self) { stations in
return stations.map { $0.name }
}
// Now I want to use the stations for other stuff.
return ClientIndexContent(client: client, stations: stations, ....)
}
let context = ClientIndexContext(clients: content)
return try req.make(LeafRenderer.self).render("clients/index", context)
}
}
My problem is that stations
is an EventLoopFuture<[String]>
instead of a [String]
. Since I'm using Leaf here I need the actual values from the clients and stations so that I can populate the content to pass into the leaf renderer.
So you have a number of ways of doing it, but basically you need to rethink how you do things in an async world. However, Vapor does provide some nice things to help this. To start with, Leaf can actually handle futures, so if you set your ClientIndexContext
to have a property of let stations: Future<[String]>
, then you can just access that inside Leaf as normal.
The other option you can do is to call map(to: [String].self)
on stations
which will get all of the futures for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With