Skip to content

Commit

Permalink
🧪 ✨ 📚 Add userInfo and improve docs.
Browse files Browse the repository at this point in the history
  • Loading branch information
connor-ricks committed Sep 15, 2024
1 parent 6fe13be commit f8abf0d
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 27 deletions.
41 changes: 16 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@ You can use `Group` to help organize your routes and cut down on the repetitiven
app.register {
Group("api", "v1") {
Group("movies") {
GET { ... }
GET("latest") { ... }
GET("popular") { ... }
GET(":movie") { ... }
}
Group("books") {
GET { ... }
GET("new") { ... }
GET("trending") { ... }
GET(":book") { ... }
Expand Down Expand Up @@ -68,17 +70,16 @@ If you have more than one middleware... no worries, `.middleware(_:)` accepts a
```swift
Group {
GET("foo") { ... }
Group {
GET("bar") { ... }
}
.middleware(Authentication(), Validator())
GET("bar") { ... }
.middleware(Authentication(), Validator())
.middleware(Reporter())
}
.middleware(Logging())
```

Remember that order matters here. Incoming requests will always execute middleware from top to bottom. So in the above example, the order of an incoming request would be as follows ➡️ `Logging`, `Authentication`, `Validator`. Outgoing respones will always execute middleware in the reverse order. ➡️ `Validator`, `Authentication`, `Logging`.
Remember that order matters here. Incoming requests will always execute middleware from the top of the tree to the bottom. So in the above example, the order of an incoming request would be as follows ➡️ `Logging`, `Reporter`, `Authentication`, `Validator`. Outgoing respones will always execute middleware in the reverse order. ➡️ `Validator`, `Authentication`, `Reporter`, `Logging`.

### Making Custom Route Components
### Custom Route Components

Often times, as your routes grow, a single large definition can become unwieldly and cumbersome to read and update. Organization of routes can be straightforward with `@RouteBuilder`

Expand Down Expand Up @@ -168,7 +169,6 @@ app.register {

For existing vapor applications, it may be unreasonable or unwieldly to rewrite your entire routing stack in one go. You can start with replacing smaller sections of your route definitions by registering a `RouteComponent` on any `RoutesBuilder` in your application.


```swift
let users = app.grouped("users")
users.get(":user") { ... }
Expand All @@ -182,25 +182,16 @@ books.register {
}
```

### RouteModifiers

- Currently undocumented.
### Route Metadata

## TODO

- [Confirmed] Implement Websocket support
- [Confirmed] Handle routes at the root of a RouteComponent.
Vapor supports adding metadata to your routes. To add your own metadata to a route within a `@RouteBuilder`, make use of either the `.description(_:)` modifier or the `.userInfo(key:value:)` modifier.

```swift
Group(":movie") {
... How do we handle JUST ":movie"?
GET("credits") { ... }
GET("category") { ... }
Group {
GET("hello") {
...
}
.description("Says hello")
.userInfo(key: "isBeta", value: true)
}
```

- [Maybe] Implement EnvironmentObject style support.
- [Maybe] Implement Service support
- [Maybe] Route modifier for description.
- [Maybe] Route modifier for caseInsensitive.
- [Maybe] Route modifier for defaultMaxBodySize.
```
34 changes: 34 additions & 0 deletions Sources/VaporRouteBuilder/RouteModifiers/UserInfoModifier.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//
// MIT License
//
// Copyright (c) 2024 Connor Ricks
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import Vapor

extension Route {
/// Adds the provided value to the route's `userInfo` dictionary at the sepcified key.
///
/// > Important: Assigning a value to a key that already has a value will overwrite the previously set value.
func userInfo(key: AnySendableHashable, value: Sendable) -> Route {
userInfo[key] = value
return self
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ extension XCTApplicationTester {
line: Int = #line,
column: Int = #column,
assertMiddleware middleware: [TestMiddleware] = [],
beforeRequest: @escaping (inout XCTHTTPRequest) async throws -> Void = { _ in }
beforeRequest: @escaping (inout XCTHTTPRequest) async throws -> Void = { _ in },
afterResponse: ((XCTHTTPResponse) async throws -> Void)? = nil
) async throws -> XCTApplicationTester {
func test() async throws -> XCTApplicationTester {
try await self.test(
Expand All @@ -48,7 +49,7 @@ extension XCTApplicationTester {
file: filePath,
line: UInt(line),
beforeRequest: beforeRequest,
afterResponse: { res async in
afterResponse: afterResponse ?? { res async in
#expect(
path == res.body.string,
sourceLocation: SourceLocation(
Expand Down
39 changes: 39 additions & 0 deletions Tests/VaporRouteBuilderTests/RouteComponents/RouteTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,43 @@ import XCTVapor
#expect(app.routes.all.count == 1)
}
}

@Test func test_route_asChildOfGroupWithoutPath_producesRouteMatchingParent() async throws {
try await Application.testing(content: {
Group("A") {
DELETE { _ in "delete" }
GET { _ in "get" }
PATCH { _ in "patch" }
POST { _ in "post" }
PUT { _ in "put" }
Route(.OPTIONS) { _ in "options" }
}
}) { app in
try await app.testing(.DELETE, "/A", afterResponse: { res in
#expect(res.body.string == "delete")
})

try await app.testing(.GET, "/A", afterResponse: { res in
#expect(res.body.string == "get")
})

try await app.testing(.PATCH, "/A", afterResponse: { res in
#expect(res.body.string == "patch")
})

try await app.testing(.POST, "/A", afterResponse: { res in
#expect(res.body.string == "post")
})

try await app.testing(.PUT, "/A", afterResponse: { res in
#expect(res.body.string == "put")
})

try await app.testing(.OPTIONS, "/A", afterResponse: { res in
#expect(res.body.string == "options")
})

#expect(app.routes.all.count == 6)
}
}
}

0 comments on commit f8abf0d

Please sign in to comment.