Explanation of the difference between request `parameters` vs. `data`

Based on the response from @tanner in slack channel
This commit is contained in:
Anton Bronnikov 2016-09-28 18:29:56 +02:00
parent f595a85e5d
commit cd03a75010
1 changed files with 17 additions and 15 deletions

View File

@ -20,11 +20,11 @@ This creates a route that matches `users/:id` where the `:id` is an `Int`. Here'
```swift
drop.get("users", ":id") { request in
guard let userId = request.parameters["id"].int else {
throw Abort.badRequest
}
guard let userId = request.parameters["id"].int else {
throw Abort.badRequest
}
return "You requested User #\(userId)"
return "You requested User #\(userId)"
}
```
@ -44,7 +44,7 @@ Our previous example with users can be further simplified.
```swift
drop.get("users", User.self) { request, user in
return "You requested \(user.name)"
return "You requested \(user.name)"
}
```
@ -54,9 +54,9 @@ Here is what this would look like if model didn't conform to `StringInitializabl
```swift
drop.get("users", Int.self) { request, userId in
guard let user = try User.find(userId) else {
throw Abort.notFound
}
guard let user = try User.find(userId) else {
throw Abort.notFound
}
return "You requested User #\(userId)"
}
@ -96,9 +96,9 @@ Type safe routing is currently limited to three path parts. This is usually reme
```swift
drop.group("v1", "users") { users in
users.get(User.self, "posts", Post.self) { request, user, post in
return "Requested \(post.name) for \(user.name)"
}
users.get(User.self, "posts", Post.self) { request, user, post in
return "Requested \(post.name) for \(user.name)"
}
}
```
@ -110,14 +110,16 @@ As shown briefly above, you are still free to do traditional routing. This can b
```swift
drop.get("v1", "users", ":userId", "posts", ":postId", "comments": ":commentId") { request in
let userId = try request.parameters.extract("userId") as Int
let postId = try request.parameters.extract("postId") as Int
let commentId = try request.parameters.extract("commentId") as Int
let userId = try request.parameters.extract("userId") as Int
let postId = try request.parameters.extract("postId") as Int
let commentId = try request.parameters.extract("commentId") as Int
return "You requested comment #\(commentId) for post #\(postId) for user #\(userId)"
return "You requested comment #\(commentId) for post #\(postId) for user #\(userId)"
}
```
> Property `request.parameters` is used to extract parameters encoded in the URI _path_ (for example, `/v1/users/1` has a parameter `:userId` equal to `"1"`). In case of parameters passed as a part of a _query_ (e.g. `/v1/search-user?userId=1`), the `request.data` should be used (e.g. `let userId = request.data["userId"]?.string`).
Request parameters can be accessed either as a dictionary or using the `extract` syntax which throws instead of returning an optional.
### Groups