Skip to content

Instantly share code, notes, and snippets.

View canapio's full-sized avatar

canapio canapio

  • Busan, South Korea
View GitHub Profile
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
final class ArrayResponseMapper<A: ParsedItem> {
static func process(obj: AnyObject?, mapper: (AnyObject? throws -> A)) throws -> [A] {
guard let json = obj as? [[String: AnyObject]] else { throw ResponseMapperError.Invalid }
var items = [A]()
for jsonNode in json {
let item = try mapper(jsonNode)
items.append(item)
}
protocol ResponseMapperProtocol {
associatedtype Item
static func process(obj: AnyObject?) throws -> Item
}
final class SignInResponseMapper: ResponseMapper<SignInItem>, ResponseMapperProtocol {
static func process(obj: AnyObject?) throws -> SignInItem {
return try process(obj, parse: { json in
let token = json["token"] as? String
class ResponseMapper<A: ParsedItem> {
static func process(obj: AnyObject?, parse: (json: [String: AnyObject]) -> A?) throws -> A {
guard let json = obj as? [String: AnyObject] else { throw ResponseMapperError.Invalid }
if let item = parse(json: json) {
return item
} else {
L.log("Mapper failure (\(self)). Missing attribute.")
throw ResponseMapperError.MissingAttribute
}
internal enum ResponseMapperError: ErrorType {
case Invalid
case MissingAttribute
}
public struct SignInItem: ParsedItem {
public let token: String
public let uniqueId: String
}
public struct UserItem: ParsedItem {
public let uniqueId: String
public let firstName: String
public protocol ParsedItem {}
public class NetworkQueue {
public static var shared: NetworkQueue!
let queue = NSOperationQueue()
public init() {}
public func addOperation(op: NSOperation) {
queue.addOperation(op)
public class SignInOperation: ServiceOperation {
private let request: SignInRequest
public var success: (SignInItem -> Void)?
public var failure: (NSError -> Void)?
public init(email: String, password: String) {
request = SignInRequest(email: email, password: password)
super.init()
public class ServiceOperation: NetworkOperation {
let service: BackendService
public override init() {
self.service = BackendService(BackendConfiguration.shared)
super.init()
}
public override func cancel() {