Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Forked from gonzalonunez/Routing.swift
Last active May 13, 2018 06:06
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chriseidhof/ebf609acbf66dbfcd4c7f43a2bf54885 to your computer and use it in GitHub Desktop.
Save chriseidhof/ebf609acbf66dbfcd4c7f43a2bf54885 to your computer and use it in GitHub Desktop.
Routing Problem
import Foundation
struct Handler {
let handleJSON: (Data) throws -> Void
init<T: Decodable>(handler: @escaping (T) -> Void) {
handleJSON = { data in
let object = try JSONDecoder().decode(T.self, from: data)
handler(object)
}
}
}
// Here's where I set up the (simplified) routing aka try to store functions in a dictionary keyed by "endpoints":
var handlers = [String: Handler]()
func register<T: Decodable>(
endpoint: String,
with handle: @escaping (T) -> Void)
{
handlers[endpoint] = Handler(handler: handle)
}
register(endpoint: "hello") { (object: String) in
print("got a string: \(object)")
}
// Here's what I'd like to do once I have data and know the endpoint:
func didReceive(data: Data, for endpoint: String) throws {
guard let handler = handlers[endpoint] else { return }
try handler.handleJSON(data)
}
struct Person: Codable {
let name: String
let age: Int
}
register(endpoint: "person", with: { (p: Person) in
dump(p)
})
try didReceive(data: try! JSONEncoder().encode(Person(name: "Foo", age: 99)), for: "person")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment