我想拥有一个索引控制器功能,如果没有设置请求参数,则返回一个实体数组;如果设置了id参数,则返回一个实体。但是,我想始终接收一个数组,在后一种情况下,它仅包含一个元素。
这是我的职能:
final class AddressController {
func index(_ req: Request) throws -> Future<[Address]> {
if let id = try? req.query.get(UUID.self, at: "id") {
// THIS IS NOT WORKING...
return Address.find(id, on: req)
} else {
return Address.query(on: req).all()
}
}
}
final class AddressController {
func index(_ req: Request) throws -> Future<[Address]> {
if let id = try? req.query.get(UUID.self, at: "id") {
return Address.find(id, on: req).map {
guard let address = $0 else { return [] }
return [address]
}
} else {
return Address.query(on: req).all()
}
}
}