💉

Swift OpenAPI Generator で自動生成コードにリクエストを注入する

に公開
1

Discussion

trickarttrickart

CurlMiddlewareとても参考になりました!

swift-openapi-runtime 1.7.0ではAPIが多少変わっていたのでそれに合わせたバージョンを書いてみたので共有いたします。

import Foundation
import HTTPTypes
import OpenAPIRuntime

// https://zenn.dev/kamimi01/articles/1bb2a5f6f2bcf0
struct CurlMiddleware: ClientMiddleware {
    let needsRedactionValues: [String: String]

    func intercept(
        _ request: HTTPRequest,
        body: HTTPBody?,
        baseURL: URL,
        operationID: String,
        next: @Sendable (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?)
    ) async throws -> (HTTPResponse, HTTPBody?) {
        var baseCommand = #"curl "\#(baseURL.absoluteString)\#(request.path ?? "")""#

        if request.method == .head {
            baseCommand += " --head"
        }

        var command = [baseCommand]

        if request.method != .get && request.method != .head {
            command.append("-X \(request.method.rawValue)")
        }

        for field in request.headerFields {
            if field.name.rawName != "Cookie" {
                let value: String
                if let needRedactionValue = needsRedactionValues[field.name.rawName] {
                    value = needRedactionValue
                } else {
                    value = field.value
                }
                command.append("-H \"\(field.name): \(value)\"")
            }
        }

        if let body {
            command.append("-d '\(body)'")
        }

        print(command.joined(separator: " \\\n\t"))

        return try await next(request, body, baseURL)
    }
}