Vapor 3-当搜索失败时,返回一个不同的未来



我正在使用Vapor 3并链接到FoundationDB数据库,所以我没有使用Fluent。我有一个搜索记录的方法,但如果它不返回记录,它显然会崩溃(因为我强制打开值(。

我想保护数据库的读取,如果没有找到记录,则返回响应。然而,这将不是未来预期的记录。我想我应该返回一个不同的响应,但不确定如何改变预期的结果。

//creates a specific country
func getCountry( req: Request) throws -> Future<Country> {
// get Country name from get parameter string
let countryString = try req.parameters.next(String.self)

// get record from Database. This could fail and so needs to be guarded. What response should be returned as the Future requires a Country datatype?
let record =  FDBConnector().getRecord(path: Subspace("iVendor").subspace(["Countries", countryString]))

let newCountry = try JSONDecoder().decode(Country.self, from: record!)
// return Country Struct
return Future.map(on: req) {return newCountry }
}

这里有几个选项。

首先,如果您从方法中抛出错误:

guard let record =  FDBConnector().getRecord(path: Subspace("iVendor").subspace(["Countries", countryString])) else {
throw Abort(.notFound, reason: "No country found with name (countryString)")
}

错误将转换为404(未找到(响应,"No country found with name (countryString)"作为错误消息。

如果您想对结果响应进行更多控制,可以将路由切换程序的返回类型更改为Future<Response>。然后,您可以将Country对象编码到响应或创建自定义错误响应。不过,这种方法确实需要一些额外的工作。

let response = Response(using: req)
guard let record =  FDBConnector().getRecord(path: Subspace("iVendor").subspace(["Countries", countryString])) else {
try response.content.encode(["message": "Country not found"])
response.http.status = .notFound
return response
}
try response.content.encode(record)
return response

请注意,如果希望该代码段工作,则必须使Country符合Content

最新更新