Create a gist now

Instantly share code, notes, and snippets.

import UIKit
import APIKit
import Himotoki
protocol GitHubRequestType: RequestType {
}
extension GitHubRequestType {
var baseURL: NSURL {
return NSURL(string: "https://api.github.com")!
}
}
extension GitHubRequestType where Response: Decodable {
func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Response {
return try decodeValue(object)
}
}
struct Repository: Decodable {
let id: Int
let fullName: String
let stargazersCount: Int
static func decode(e: Extractor) throws -> Repository {
return try Repository(
id: e.value("id"),
fullName: e.value("full_name"),
stargazersCount: e.value("stargazers_count")
)
}
}
struct SearchResponse<Item: Decodable>: Decodable {
let items: [Item]
static func decode(e: Extractor) throws -> SearchResponse<Item> {
return try SearchResponse(items: e.array("items"))
}
}
// https://developer.github.com/v3/search/#search-repositories
struct SearchRepositoriesRequest: GitHubRequestType {
enum Sort: String {
case Stars = "stars"
case Forks = "forks"
case Updated = "updated"
}
let query: String
let sort: Sort
// MARK: RequestType
typealias Response = SearchResponse<Repository>
var method: HTTPMethod {
return .GET
}
var path: String {
return "/search/repositories"
}
var parameters: AnyObject? {
return [
"q": query,
"sort": sort.rawValue,
]
}
}
class ViewController: UIViewController {
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let request = SearchRepositoriesRequest(query: "APIKit", sort: .Stars)
Session.sendRequest(request) { result in
switch result {
case .Success(let response):
for repository in response.items {
print("\(repository.fullName) 🌟\(repository.stargazersCount)")
}
case .Failure(let error):
print("error: \(error)")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment