diff --git a/4.0/docs/routing/groups.md b/4.0/docs/routing/groups.md new file mode 100644 index 00000000..11c3079f --- /dev/null +++ b/4.0/docs/routing/groups.md @@ -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") { ... } +``` \ No newline at end of file diff --git a/4.0/mkdocs.yml b/4.0/mkdocs.yml index c675bf1f..7f3bfe1c 100644 --- a/4.0/mkdocs.yml +++ b/4.0/mkdocs.yml @@ -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'