Skip to content

Commit 0491598

Browse files
committed
chore: allow absent data in ToManyRelationship
1 parent c5d1e71 commit 0491598

3 files changed

Lines changed: 29 additions & 5 deletions

File tree

Sources/JSONAPI/Resource/Relationship.swift

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -401,16 +401,24 @@ extension ToManyRelationship: Codable {
401401
links = try container.decode(LinksType.self, forKey: .links)
402402
}
403403

404-
var identifiers: UnkeyedDecodingContainer
404+
var identifiers: UnkeyedDecodingContainer?
405405
do {
406406
identifiers = try container.nestedUnkeyedContainer(forKey: .data)
407407
} catch let error as DecodingError {
408-
guard case let .typeMismatch(type, context) = error,
409-
type is _ArrayType.Type else {
410-
throw error
411-
}
408+
switch error {
409+
case let .typeMismatch(type, context) where type is _ArrayType.Type:
412410
throw JSONAPICodingError.quantityMismatch(expected: .many,
413411
path: context.codingPath)
412+
case .keyNotFound(ResourceLinkageCodingKeys.data, _):
413+
identifiers = nil
414+
default:
415+
throw error
416+
}
417+
}
418+
419+
guard var identifiers = identifiers else {
420+
idsWithMeta = []
421+
return
414422
}
415423

416424
var newIds = [ID]()

Tests/JSONAPITests/Relationships/RelationshipTests.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,14 @@ extension RelationshipTests {
235235
test_DecodeEncodeEquality(type: ToManyWithMetaAndLinks.self,
236236
data: to_many_relationship_with_meta_and_links)
237237
}
238+
239+
func test_ToManyRelationshipWithMetaNoData() {
240+
let relationship = decoded(type: ToManyWithMeta.self,
241+
data: to_many_relationship_with_meta_no_data)
242+
243+
XCTAssertEqual(relationship.ids, [])
244+
XCTAssertEqual(relationship.meta.a, "hello")
245+
}
238246
}
239247

240248
// MARK: Nullable

Tests/JSONAPITests/Relationships/stubs/RelationshipStubs.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,3 +241,11 @@ let to_many_relationship_type_mismatch = """
241241
]
242242
}
243243
""".data(using: .utf8)!
244+
245+
let to_many_relationship_with_meta_no_data = """
246+
{
247+
"meta": {
248+
"a": "hello"
249+
}
250+
}
251+
""".data(using: .utf8)!

0 commit comments

Comments
 (0)