Swift OpenAPI Hummingbird

Hummingbird 传输,用于 OpenAPI 生成器

// Create your router.
let router = Router()

// Create an instance of your handler type that conforms the generated protocol
// defining your service API.
let api = MyServiceAPIImpl()

// Call the generated function on your implementation to add its request
// handlers to the app.
try api.registerHandlers(on: router)

// Create the application and run as you would normally.
let app = Application(router: router)
try await app.runService()

RequestContext

在 OpenAPI 端点中使用路由器 RequestContext 是一个常见的需求。 你可以通过添加一个中间件来实现这一点,该中间件将你的 RequestContext 类型存储在 TaskLocal 中。

struct RequestContextMiddleware: RouterMiddleware {
    typealias Context = MyRequestContext
    @TaskLocal static var requestContext: Context?

    func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response {
        try await Self.$requestContext.withValue(context) {
            try await next(request, context)
        }
    }
}

如果你添加此中间件的一个版本,并将 MyRequestContext 替换为你自己的 RequestContext 类型,添加到你的路由器中间件链的末尾,那么它将通过 RequestContextMiddleware.requestContext 在你的 OpenAPI 端点中可用。

文档

要开始使用,请查看完整的 文档,其中包含逐步教程!