Last active
January 4, 2017 03:10
-
-
Save kaiobrito/c966bbd84ce586e29ea0564c304c4f7c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol JSONMappable { | |
init(json: JSON) | |
} | |
struct GHUser: JSONMappable { | |
var login: String | |
var id: String | |
init(json: JSON) { | |
self.login = json["login"].stringValue | |
self.id = json["id"].stringValue | |
} | |
} | |
struct GHRepository: JSONMappable { | |
var id: String | |
var name: String | |
init(json: JSON) { | |
self.name = json["name"].stringValue | |
self.id = json["id"].stringValue | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SearchableWebService<T: JSONMappable> { | |
typealias SearchResponseHandler = (([T]) -> Void) | |
func searchURL(withTerm term: String) -> URL { | |
fatalError() | |
} | |
func search(term: String, handler: SearchResponseHandler? = nil) { | |
let url = self.searchURL(withTerm: term) | |
let task = URLSession.shared.dataTask(with: url) { data, _ , _ in | |
if let data = data { | |
let json = JSON(data: data) | |
handler?(json["items"].arrayValue.map(T.init)) | |
} | |
} | |
task.resume() | |
} | |
} | |
class GHRepositoryWebService: SearchableWebService<GHRepository> { | |
override func searchURL(withTerm term: String) -> URL { | |
return URL(string:"https://api.github.com/search/repositories?q=\(term)")! | |
} | |
} | |
class GHUserWebService: SearchableWebService<GHUser> { | |
override func searchURL(withTerm term: String) -> URL { | |
return URL(string:"https://api.github.com/search/users?q=\(term)")! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment