Swifter as proxy server
In my application, there are a lot of calls to the backend and using stubs for everyone is impossible. Therefore, I wanted to send most of the requests for a real backend and only get the necessary data from the swifter. So I wanted to use swifter as a proxy server. I found a recent discussion about this https://github.com/httpswift/swifter/issues/376#issuecomment-481514351
Please share exapmle of code if you used swifter as a proxy server or you know how to do it easily. This code can be added to the documentation.
@venigreat I'm using it like this:
class LocalServer {
enum LocalServerError: Error {
// ...
}
struct Request {
let path: String
}
typealias StreamCallback = (@escaping (Result<Data, Error>) throws -> Void) -> Void
typealias HandlerCallback = (Request) -> (Result<StreamCallback, LocalServerError>)
var routeHandler: HandlerCallback?
init(port: Int = 0) {
server.notFoundHandler = { [weak self] request in
let onError: (LocalServerError) -> HttpResponse = {
HttpResponse.badRequest(.json("{ \"error\": \"\($0.localizedDescription)\"}"))
}
guard let handler = self?.routeHandler?(LocalServer.Request.from(request)) else {
return onError(.missingRouteHandler)
}
switch handler {
case let .failure(error):
return onError(error)
case let .success(streamReader):
return HttpResponse.raw(200, "OK", nil) { writer in
streamReader { result in
switch result {
case let .failure(error):
throw error
case let .success(data):
try writer.write(data)
}
}
}
}
}
}
}
I'm looking at this same issue, but I can't see how the suggested code actually calls out to another server. Is there an implementation of routeHandler missing from the example?
Currently I'm thinking I'll need to wrap an implementation of URLSession and map it's response back into the matching Swifter response.
@drekka At the end, we had to: (╯°□°)╯︵ ┻━┻ and switch to something that supports async functionality (GCDWebServer)