Ship is a APIKit plugin that can inject common processing to requests on APIKit.
struct RequestDependency: Dependency {
var baseURL: URL
var accessToken: String
func buildBaseURL<R: APIRequest>(_ request: R) -> URL {
return baseURL
}
func buildHeaderFields<R: APIRequest>(_ request: R) -> [String: String] {
var headerFields = request.headerFields
headerFields["authorization"] = "Bearer \(accessToken)"
return headerFields
}
}
let session = Session(dependency: RequestDependency())
APIKit is a type-safe networking abstraction layer that is super cool.
- Swift 5.0
Add the following to your Podfile
:
pod "Ship"
Add the following to your Cartfile
:
github "cats-oss/Ship"
The advantage of Ship is that common processing can be injected.
func buildBaseURL<R: Request>(_ request: R) -> URL
func buildHeaderFields<R: Request>(_ request: R) -> [String: String]
Called each time a request is created. Return the base URL and request header.
func intercept<R: Request>(request: R, urlRequest: URLRequest) throws -> URLRequest
Called each time a request is created. Change the request as needed.
func intercept<R: Request>(request: R, object: Any, urlResponse: HTTPURLResponse) throws -> Any
Called each time of response. Change the response object as needed.
func buildBaseURL<R: APIRequest>(_ request: R) -> URL {
return URL(string: "https://example.com")!
}
func buildHeaderFields<R: APIRequest>(_ request: R) -> [String: String] {
var headerFields = request.headerFields
headerFields["authorization"] = "Token"
return headerFields
}
Ship's Request inherits APIKit's Request.
var basePathComponent: Component? { get }
Return the base path component.
var basePathComponent: AnyBasePathComponent? {
return AnyBasePathComponent(basePath: "/v3")
}
Can define the components of the request base path.
var basePath: String? { get }
Return the string that is the basis of the path.
- Component
enum APIVersion: String, RequestBasePathComponent {
case undefined
case v1
case v2
var basePath: String? {
switch self {
case .undefined:
return nil
default:
return "/\(rawValue)"
}
}
}
- Request
extension Request {
var basePathComponent: APIVersion? {
return .v1
}
}
struct GetUserRequest: Request {
typealias Response = User
let method = HTTPMethod.get
let path = "/me"
}
- Dependency
struct RequestDependency: Dependency {
func buildBaseURL<R: APIRequest>(_ request: R) -> URL {
return URL(string: "https://example.com")!
}
}
The session makes a URL like following:
https://example.com/v1/me
Under the MIT license. See LICENSE file for details.