Created
August 16, 2019 12:24
-
-
Save manishkkatoch/3f308595502790c79156bacf9e860883 to your computer and use it in GitHub Desktop.
HATEOAS Resource
This file contains 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
typealias LinkAvailableHandler = (Link) -> Void | |
typealias LinkUnAvailableHandler = () -> Void | |
protocol RestResource: Decodable { | |
associatedtype modelType where modelType : Decodable | |
var item: modelType? {get} | |
var links: Array<Link> { get } | |
} | |
extension RestResource { | |
func hasCapability(for linkName: String) -> Bool { | |
return links.contains { $0.rel == linkName } | |
} | |
func getRelation(forRel linkItem: String) -> Link? { | |
return links.filter { $0.rel == linkItem }.first | |
} | |
func capabilityMap(forRel: String,_ onAvailable: LinkAvailableHandler? = nil,_ onUnavailable: LinkUnAvailableHandler? = nil) { | |
if let link = self.getRelation(forRel: forRel) { | |
onAvailable?(link) | |
} else { | |
onUnavailable?() | |
} | |
} | |
} | |
struct Resource<T>: RestResource where T : Decodable { | |
typealias modelType = T | |
let item : T? | |
var links: Array<Link> = Array<Link>() | |
enum CodingKeys: String, CodingKey { | |
case links = "_links" | |
} | |
init(from decoder: Decoder) throws { | |
let values = try decoder.container(keyedBy: CodingKeys.self) | |
links = try values.decode([Link].self, forKey: .links) | |
item = try T.init(from: decoder) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment