TestsTested | ✗ |
LangLanguage | SwiftSwift |
License | MIT |
ReleasedLast Release | Mar 2017 |
SwiftSwift Version | 3.0 |
SPMSupports SPM | ✗ |
Maintained by JPAlary.
This Interceptor “concept” comes from the Interceptor implementation in the library Okhttp for Android (see Okhttp interceptor wiki). This mechanism is very powerful when you want to modify/do some actions on an input object before and after the process it was given for. See the interceptors as a middleware between the source of your input object and its final destination.
In this Swift implementation, two more things has been added:
With Interceptors, you have:
To finish, as it’s generic, you can apply this mechanism in another context. Be creative ! :)
First thing to do, it’s to create the Interceptor(s) you need. Remember, Interceptor is designed to be used to intercept the input object. Group your Interceptors by concern and avoid duplicated ones
To do so, you just have to conform to the protocol Interceptor:
protocol Interceptor {
associatedtype Input
func intercept(chain: InterceptorChain<Input>, completion: (Input) -> Void) -> Void
}
Intercept the input
struct MyInterceptor: Interceptor {
func intercept(chain: InterceptorChain<URLRequest>, completion: (URLRequest) -> Void) -> Void {
// 1) Retrieve the input object (the request)
var request = chain.input
// 2) Do things with/on the request
// 3) Give it back to the chain
chain.input = request
// 4) Continue the chaining to others interceptors. /!\ Don't forget to call this, if you don't, you will get stuck in this interceptor.
chain.proceed(completion: completion)
}
}
When you have your interceptors implemented, it’s finished !
To launch the process:
// 1) I create an instance of interceptor chain. You can add many interceptor you want.
let chain = InterceptorChain()
.add(interceptor: AnyInterceptor(base: MyInterceptor()))
chain.input = request
// 2) Launch the process
chain.proceed { (request) in
// 3) I get my request intercepted by all the interceptors
}
For more explanations about the interceptor mechanism, don’t hesitate to read the documentation in the okhttp wiki. For RxSwift fans, there is the same implementation with RxSwift, see SwiftRxInterceptor.