File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change @@ -136,6 +136,24 @@ public extension RoutedHTTPHandler {
136
136
}
137
137
}
138
138
139
+ public extension RoutedHTTPHandler {
140
+
141
+ static func handleMatchedRequest(
142
+ isolation: isolated ( any Actor ) ? = #isolation,
143
+ _ request: HTTPRequest ,
144
+ to route: HTTPRoute ,
145
+ handler: ( HTTPRequest ) async throws -> HTTPResponse
146
+ ) async throws -> HTTPResponse ? {
147
+ if await route ~= request {
148
+ return try await HTTPRequest . $matchedRoute. withValue ( route) {
149
+ _ = isolation
150
+ return try await handler ( request)
151
+ }
152
+ }
153
+ return nil
154
+ }
155
+ }
156
+
139
157
extension RoutedHTTPHandler: RangeReplaceableCollection {
140
158
public typealias Index = Array< Element> . Index
141
159
public typealias Element = ( route: HTTPRoute , handler: any HTTPHandler )
Original file line number Diff line number Diff line change @@ -124,6 +124,39 @@ struct RoutedHTTPHandlerTests {
124
124
try await handler. handleRequest ( . make( " /450/hello?food=shrimp&qty=🍤 " ) ) . bodyString == " 900 shrimp 🍤 "
125
125
)
126
126
}
127
+
128
+ @Test
129
+ func handleMatchedRequest_matches( ) async throws {
130
+ // given
131
+ let request = HTTPRequest . make ( " /10/hello?food=fish&qty=🐟 " )
132
+ let route = HTTPRoute ( " GET /:id/hello?food=:food&qty=:qty " )
133
+
134
+ // when
135
+ let response = try await RoutedHTTPHandler . handleMatchedRequest ( request, to: route) {
136
+ #expect( $0. routeParameters [ " id " ] == " 10 " )
137
+ #expect( $0. routeParameters [ " food " ] == " fish " )
138
+ #expect( $0. routeParameters [ " qty " ] == " 🐟 " )
139
+ return HTTPResponse ( statusCode: . ok)
140
+ }
141
+
142
+ // then
143
+ #expect( response? . statusCode == . ok)
144
+ }
145
+
146
+ @Test
147
+ func handleMatchedRequest_skips( ) async throws {
148
+ // given
149
+ let request = HTTPRequest . make ( " /chips " )
150
+ let route = HTTPRoute ( " GET /fish " )
151
+
152
+ // when
153
+ let response = try await RoutedHTTPHandler . handleMatchedRequest ( request, to: route) { _ in
154
+ return HTTPResponse ( statusCode: . ok)
155
+ }
156
+
157
+ // then
158
+ #expect( response? . statusCode == nil )
159
+ }
127
160
}
128
161
129
162
private struct MockHandler : HTTPHandler {
You can’t perform that action at this time.
0 commit comments