A tiny protocol-oriented network layer written in Swift
Define your different endpoints using an enum:
enum Endpoint {
case user
case confirmationCode
}
And make that endpoint conform to the Path protocol:
protocol Path {
var baseURL: String { get }
var path: String { get }
}
extension Endpoint: Path {
var baseURL: String {
return "http://localhost:8080/"
}
var path: String {
switch self {
case .user:
return "user-information"
case .confirmationCode:
return "confirmation-code"
}
}
}
struct Resource<A> {
let endpoint: Endpoint
let method: HttpMethod<Any>
let parser: Any -> A?
}
A Resource holds the endpoint you will query, the http method (get, post, etc) and a parser closure that parse JSON to an object of type A.
struct User {
let username: String
}
extension User {
init?(dictionary: [String: Any]) {
guard let username = dictionary["username"] as? String else { return nil }
self.username = username
}
}
func queryUserEndpoint() {
let parameters = ["username": "test"]
let userResource = Resource<User>(endpoint: Endpoint.user, method: .post(parameters)) { json in
guard let dictionary = json as? [String: Any] else { return nil }
return User.init(dictionary: dictionary)
}
let ws = Netto()
ws.loadResource(userResource) { [weak self] (user, response, error) in
// handle response
}
}
If you want to set some default behaviour to your requests, use the NettoActions protocol:
protocol NettoActions {
var setDefaultRequest: (inout URLRequest -> Void)? { get }
}
extension Netto: NettoActions {
var setDefaultRequest: (inout URLRequest -> Void)? { return
{ request in
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
}
}
}
Other actions will be added in the future, like willSendRequest, didReceiveResponse, etc.
Finally, you can also define custom behaviour only on specific requests, for example:
...
let requestClosure: (inout URLRequest) -> Void = { request in
guard let token = KeychainWrapper.stringForKey("bearer") else { return }
request.addValue(token, forHTTPHeaderField: "Authorization")
}
ws.loadResource(resource, requestPlugin: requestClosure) { users, response, error in
// handle response
}
Twitter: @gusta_nas
Website: gustanas.co