swift-server / async-http-client

HTTP client library built on SwiftNIO
https://swiftpackageindex.com/swift-server/async-http-client/main/documentation/asynchttpclient
Apache License 2.0
904 stars 114 forks source link

support middlewares #393

Open weissi opened 3 years ago

weissi commented 3 years ago

[initial suggestion from @Lukasa]

AHC should support a "middleware" concept (ideally once it's a "3-tier library") where a user can supply some middlewares which do common jobs like following redirects, authenticating requests, etc.

Very rough API sketch

final class AuthenticationMiddleware {
    // rough sketch, in reality returning just one modified request isn't good enough because with redirects we may
    // need more.
    func willPerformRequest(_ request: Request, http: HTTPService) -> EventLoopFuture<Request> {
        http.client().get("auth/produce/me/an/auth/token").map { token in
            var request = request
            request.headers[.authorization] = "bearer \(token)"
            return request
        }
    }
}

func makeTwoAuthenticatedHTTPRequests(http: HTTPService, eventLoop: EventLoop, logger: Logger) {
    let client = http.client(tlsConfiguration: ...,
                             eventLoop: eventLoop,
                             logger: logger,
                             middlewares: [AuthenticationMiddleware.self])

    return client.get("https://foo/bar").flatMap { first in
        client.get("https://bar/buz").flatMap { second in
            return (first, second)
        }
    }
}
weissi commented 3 years ago

Service discovery could also be an idea for a middleware

weissi commented 1 year ago

Further ideas for middlewares: