-
-
Save chriseidhof/ebf609acbf66dbfcd4c7f43a2bf54885 to your computer and use it in GitHub Desktop.
Routing Problem
This file contains hidden or 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
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