我在一个网络上工作,我有属于特定“类别”的“帖子”,所以,当我列出帖子时,我想显示类别名称,所以我做了:
private func getCategory(from id: UUID, andRequest req: Request) -> EventLoopFuture<String> {
let categoryField = BlogCategoryModel.find(id, on: req.db).map { cat in
return cat?.title ?? "Unknown"
}
return categoryField
}
所以,我不知道如何使用它EventLoopFuture<String>
来获取我需要的字符串。
更新:
我要给你更多的背景。
所以,我有一个控制器来显示元素列表:
protocol ListController: ModelController {
func listView(req: Request) throws -> EventLoopFuture<View>
func listTable(_ models: [Model], req: Request) -> Table
func listContext(req: Request, table: Table) -> ListContext
}
public struct ListContext: Encodable {
public let title: String
public let table: Table
internal init(title: String, table: Table) {
self.title = title
self.table = table
}
}
extension ListController {
func listContext(req: Request, table: Table) -> ListContext {
.init(title: Model.name.plural.capitalized, table: table)
}
func listView(req: Request) throws -> EventLoopFuture<View> {
Model.query(on: req.db)
.all()
.map { listTable($0, req: req) }
.flatMap { table in
req.view.render("Common/List", listContext(req: req, table: table))
}
}
}
然后,我可以使用这个协议来展示任何类型的模型。在这种情况下,我想显示类别为父亲的博客:
struct BlogPostAdminController: ListController{
typealias Model = BlogPostModel
func listTable(_ models: [Model], req: Request) -> Table {
Table(columns: ["image", "title", "category"], rows: models.map { model in
TableRow(id: model.id!.uuidString, cells: [
TableCell(type: .image, model.image),
TableCell(model.title),
TableCell(getCategory(from: model.$category.id, andRequest: req)),
])
})
}
private func getCategory(from id: UUID, andRequest req: Request) -> EventLoopFuture<String> {
let categoryField = BlogCategoryModel.find(id, on: req.db).map { cat in
return cat?.title ?? "Unknown"
}
return categoryField
}
}