Query Parameters
请求查询参数可以作为字典进行访问,也可以使用extrac
进行提取参数值而不是返回可选类型。
Optional Syntax
可选语法是处理可选查询参数的最简单方法。
drop.get("comments") { request in
if let rating = request.query?["rating"]?.int {
return "You requested comments with rating greater than #\(rating)"
}
return "You requested all comments"
}
Extract Syntax
提取语法可能有助于强制查询参数的存在,如果参数不存在则抛出异常。使用这种语法,首先需要确保查询对象存在。
drop.get("comments") { request in
guard let rating = request.query?["rating"]?.int else {
throw Abort.custom(status: .preconditionFailed, message: "Please include a rating")
}
return "You requested comments with rating greater than #\(rating)"
}
继续学习vapor学习教程-目录