Plugin 2.swift 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import Foundation
  2. import Result
  3. /// A Moya Plugin receives callbacks to perform side effects wherever a request is sent or received.
  4. ///
  5. /// for example, a plugin may be used to
  6. /// - log network requests
  7. /// - hide and show a network activity indicator
  8. /// - inject additional information into a request
  9. public protocol PluginType {
  10. /// Called to modify a request before sending.
  11. func prepare(_ request: URLRequest, target: TargetType) -> URLRequest
  12. /// Called immediately before a request is sent over the network (or stubbed).
  13. func willSend(_ request: RequestType, target: TargetType)
  14. /// Called after a response has been received, but before the MoyaProvider has invoked its completion handler.
  15. func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType)
  16. /// Called to modify a result before completion.
  17. func process(_ result: Result<Moya.Response, MoyaError>, target: TargetType) -> Result<Moya.Response, MoyaError>
  18. }
  19. public extension PluginType {
  20. func prepare(_ request: URLRequest, target: TargetType) -> URLRequest { return request }
  21. func willSend(_ request: RequestType, target: TargetType) { }
  22. func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType) { }
  23. func process(_ result: Result<Moya.Response, MoyaError>, target: TargetType) -> Result<Moya.Response, MoyaError> { return result }
  24. }
  25. /// Request type used by `willSend` plugin function.
  26. public protocol RequestType {
  27. // Note:
  28. //
  29. // We use this protocol instead of the Alamofire request to avoid leaking that abstraction.
  30. // A plugin should not know about Alamofire at all.
  31. /// Retrieve an `NSURLRequest` representation.
  32. var request: URLRequest? { get }
  33. /// Authenticates the request with a username and password.
  34. func authenticate(user: String, password: String, persistence: URLCredential.Persistence) -> Self
  35. /// Authenticates the request with an `NSURLCredential` instance.
  36. func authenticate(usingCredential credential: URLCredential) -> Self
  37. }