Last active
November 18, 2016 04:05
-
-
Save lukesutton/42d5d785126a0ea0ab913b8bdb7a8474 to your computer and use it in GitHub Desktop.
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
// authentication | |
// client/account specific info | |
// urls | |
// data format transformations; flattening etc | |
// declarative data transform | |
// - flatten | |
// - rename | |
// - convert | |
// - renaming | |
// - blacklist/whitelist | |
typealias JSON = Dictionary<String, String> | |
struct Transform { | |
enum Result { | |
case success(JSON) | |
case failure(String) | |
} | |
let convert: (JSON) -> Result | |
static func rename(from: String, to: String) -> Transform { | |
return Transform { _ in | |
return .failure("Oops") | |
} | |
} | |
} | |
let transforms: [Transform] = [ | |
.rename(from: "derp", to: "herp"), | |
.rename(from: "YES", to: "NO") | |
] | |
extension Pipeline { | |
typealias Config = Dictionary<String, Any> | |
typealias Factory<C> = (Config) -> ((C, JSON) -> TransformResult)? | |
typealias Registry = Dictionary<String, Factory> | |
private static func defaultRegistry() -> [String: Factory<C>] { | |
return [ | |
"rename": { config in | |
guard let from = config["from"] as? String, | |
to = config["to"] as? String | |
else { return nil } | |
let needed = config["needed"] ?? true | |
return .rename(from: from, to: to, needed: needed) | |
} | |
] | |
} | |
// This is just a sneaky way to capture types for the closure | |
static func factory(fromBlock: Factory<C>) -> Factory<C> { | |
return fromBlock | |
} | |
static func hydrate(json: [Config], withRegistry: Registry? = nil) -> Pipeline<C>? { | |
let registry = withRegistry ?? defaultRegistry | |
let transforms = json.map { config in | |
guard let name = config["name"] else { return nil } | |
guard let factory = registry[name] else { return nil } | |
return factory(config) | |
} | |
return nil | |
} | |
} | |
Pipeline.hydrate(json: ) | |
enum TransformFailure { | |
case fieldMissing(field: String, message: String?) | |
case unexpectedType(field: String, expected: String, found: String, message: String?) | |
case other(field: String, message: String?, error: ErrorType?) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment