Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions JSONAPIModel/JSONAPIFactory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ public final class JSONAPIFactory: Collection {
guard let model = createModel(id: id, type: modelType) else {
return nil
}

try model.loadAttributes(json)
model.loadRelationships(self, json: json)
return model
Expand Down
46 changes: 45 additions & 1 deletion JSONAPIModel/JSONAPIModelType.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,51 @@ extension JSONAPIModelType {
/// - Parameters factory: factory for creating JSON API model
/// - Parameters store: JSON API store that contains included payload
public func loadIncluded(_ factory: JSONAPIFactory, store: JSONAPIStore) throws {
try loadIncludedIterative(factory, store: store)
let meta = Self.metadata
// load attributtes and relationships from the data we found in store
if let json = store.get(type: meta.type, id: id) {
try loadAttributes(json)
loadRelationships(factory, json: json)
}

for relationship in meta.relationships {
switch relationship.type {
case .singular(let getter, let setter):
guard let model = getter(self) else {
continue
}
let modelMeta = type(of: model).metadata
guard let modelJSON = store.get(type: modelMeta.type, id: model.id) else {
setter(self, nil)
continue
}
guard let newModel = try factory.createModel(modelJSON) else {
setter(self, nil)
continue
}
try newModel.loadIncluded(factory, store: store)
setter(self, newModel)
case .multiple(let getter, let setter):
let models = getter(self)
var newModels: [JSONAPIModelType] = []
for model in models {
let modelMeta = type(of: model).metadata
guard let modelJSON = store.get(type: modelMeta.type, id: model.id) else {
// looks like we cannot find json in store, just add the old one
newModels.append(model)
try model.loadIncluded(factory, store: store)
continue
}
// try to create the model again from the included payload
guard let newModel = try factory.createModel(modelJSON) else {
continue
}
try newModel.loadIncluded(factory, store: store)
newModels.append(newModel)
}
setter(self, newModels)
}
}
}

/// Load relationships from given JSON API store using iterative approach (safer than recursive)
Expand Down