Merge pull request #26 from eneko/patch-1

Add Query Parameters page to Routing section
This commit is contained in:
Casper Rasmussen 2017-01-13 20:03:51 +01:00 committed by GitHub
commit 5643cb3a1c
2 changed files with 38 additions and 1 deletions

View File

@ -78,8 +78,11 @@ menu:
text: Basic
relativeUrl: routing/basic.html
routing-parameters:
text: Parameters
text: Route Parameters
relativeUrl: routing/parameters.html
routing-query-parameters:
text: Query Parameters
relativeUrl: routing/query-parameters.html
routing-group:
text: Group
relativeUrl: routing/group.html

View File

@ -0,0 +1,34 @@
---
currentMenu: routing-query-parameters
---
# Query Parameters
Request query parameters can be accessed either as a dictionary or using the `extract` syntax which throws instead of returning an optional.
## Optional Syntax
Optional syntax is the easiest way to handle optional query parameters.
```swift
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
Extract syntax might be useful to *enforce* the presence of query parameters and throw an exception if they are not present.
To use this syntax first we need to ensure the query object is present with a `guard`.
```swift
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)"
}
```