add route groups section

This commit is contained in:
tanner0101 2019-10-25 13:55:21 -04:00
parent 9f1282b71f
commit fd49bc7571
2 changed files with 92 additions and 0 deletions

View File

@ -0,0 +1,91 @@
# Route Groups
Route grouping allows you to create a set of routes with a path prefix or specific middleware. Grouping supports a builder and closure based syntax.
All grouping methods return a `RouteBuilder` meaning you can infinitely mix, match, and nest your groups with other route building methods.
## Path Prefix
Path prefixing route groups allow you to prepend one or more path components to a group of routes.
```swift
let users = app.grouped("users")
// GET /users
users.get { req -> String in
...
}
// POST /users
users.post { req -> String in
...
}
// GET /users/:id
users.get(":id") { req -> String in
let id = req.parameters.get("id")!
...
}
```
Any path component you can pass into methods like `get` or `post` can be passed into `grouped`. There is an alternative, closure-based syntax as well.
```swift
app.group("users") { users in
// GET /users
users.get { req -> String in
fatalError("...")
}
// POST /users
users.post { req -> String in
fatalError("...")
}
// GET /users/:id
users.get(":id") { req -> String in
let id = req.parameters.get("id")!
fatalError("...")
}
}
```
Nesting path prefixing route groups allows you to concisely define CRUD APIs.
```swift
app.group("users") { users in
// GET /users
users.get { ... }
// POST /users
users.post { ... }
users.group(":id") { user in
// GET /users/:id
user.get { ... }
// PATCH /users/:id
user.patch { ... }
// PUT /users/:id
user.put { ... }
}
}
```
## Middleware
In addition to prefixing path components, you can also add middleware to route groups.
```swift
app.get("fast-thing") { req in
...
}
app.group(RateLimitMiddleware(requestsPerMinute: 5)) { rateLimited in
rateLimited.get("slow-thing") { req in
...
}
}
```
This is especially useful for protecting subsets of your routes with different authentication middleware.
```swift
app.post("login") { ... }
let auth = app.grouped(AuthMiddleware())
auth.get("dashboard") { ... }
auth.get("logout") { ... }
```

View File

@ -36,6 +36,7 @@ nav:
- 'Routing':
- 'Overview': 'routing/overview.md'
- 'Routes': 'routing/routes.md'
- 'Groups': 'routing/groups.md'
- 'Version (4.0)':
- '1.5': 'version/1_5.md'
- '2.0': 'version/2_0.md'