refactored Category to include the mapping handler Dictionary
added methods to register and get handlers
This commit is contained in:
parent
bad4c67e9e
commit
473da43e6b
@ -25,24 +25,59 @@ public struct ModelRegistry {
|
||||
var name: String
|
||||
var codingKey: String
|
||||
var instanceTypes: [String: ModelProtocol.Type] = [:]
|
||||
var handlerTypes: [String: ModelHandlerProtocol.Type] = [:]
|
||||
}
|
||||
|
||||
private static var categories: [String: Category] = [:]
|
||||
|
||||
/// Registers models for Atomic use.
|
||||
public static func register<H: ModelHandlerProtocol, M: ModelProtocol>(handler: H.Type, for model: M.Type) throws {
|
||||
//register the type
|
||||
try self.register(model)
|
||||
|
||||
//get the key for the handler
|
||||
let key = model.identifier
|
||||
|
||||
//get the category for the ModelProtocol
|
||||
var category = getCategory(for: model)
|
||||
|
||||
// Check to ensure the Category/Container combination doesn't exist.
|
||||
if category.handlerTypes[key] != nil {
|
||||
throw ModelRegistry.Error.other(message: "ModelHandlerProtocol: \(String(describing: handler)) already exists in Category: \(category.name)")
|
||||
} else {
|
||||
category.handlerTypes[key] = handler
|
||||
}
|
||||
categories[category.name] = category
|
||||
}
|
||||
|
||||
/// Registers models for Atomic use.
|
||||
public static func register<M: ModelProtocol>(_ type: M.Type) throws {
|
||||
|
||||
var category = categories[M.categoryName] ?? Category(name: M.categoryName, codingKey: M.categoryCodingKey)
|
||||
//get the category for the ModelProtocol
|
||||
var category = getCategory(for: type)
|
||||
|
||||
// Check to ensure the Category/Type combination doesn't exist.
|
||||
if category.instanceTypes[M.identifier] != nil {
|
||||
throw ModelRegistry.Error.other(message: "ModelProtocol: \(M.identifier) already exists in Category: \(M.categoryName)")
|
||||
}
|
||||
|
||||
category.instanceTypes[M.identifier] = type
|
||||
categories[M.categoryName] = category
|
||||
}
|
||||
|
||||
public static func getHandler(_ model: ModelProtocol) -> ModelHandlerProtocol.Type? {
|
||||
//get the modelType
|
||||
let modelType = type(of: model)
|
||||
|
||||
//get the category for the ModelProtocol
|
||||
guard let category = categories[modelType.categoryName] else { return nil }
|
||||
|
||||
//get the containerProtocol for this ModelProtocol you had registered
|
||||
return category.handlerTypes[modelType.identifier]
|
||||
}
|
||||
|
||||
private static func getCategory<M: ModelProtocol>(for type: M.Type) -> Category {
|
||||
return categories[type.categoryName] ?? Category(name: type.categoryName, codingKey: type.categoryCodingKey)
|
||||
}
|
||||
|
||||
private static func getCategory<T>(for type: T.Type) -> Category? {
|
||||
// Temporary code till we find a better solution.
|
||||
//if this is a protocol composotion, loop through each protocol for a category lookup
|
||||
|
||||
Loading…
Reference in New Issue
Block a user