Skip to content

Commit 47ebf5b

Browse files
authored
Merge pull request #21 from swift-server/task-local-readme
Add RequestContext section to README.md
2 parents 026b50b + 5694131 commit 47ebf5b

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,25 @@ let app = Application(router: router)
1919
try await app.runService()
2020
```
2121

22+
## RequestContext
23+
24+
It is a common requirement that the router `RequestContext` is used in OpenAPI endpoints. You can do this by adding a middleware that stores your RequestContext type in a TaskLocal.
25+
26+
```swift
27+
struct RequestContextMiddleware: RouterMiddleware {
28+
typealias Context = MyRequestContext
29+
@TaskLocal static var requestContext: Context?
30+
31+
func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response {
32+
try await Self.$requestContext.withValue(context) {
33+
try await next(request, context)
34+
}
35+
}
36+
}
37+
```
38+
39+
If you add a version of this middleware, replacing `MyRequestContext` with your own `RequestContext` type, to the end of your router middleware chain then it will be available from your OpenAPI endpoints via `RequestContextMiddleware.requestContext`.
40+
2241
## Documentation
2342

2443
To get started, check out the full [documentation][docs-generator], which contains step-by-step tutorials!

0 commit comments

Comments
 (0)