Skip to content

Commit 3047e2d

Browse files
committed
Add access to computed attributes that are not AttributeType
1 parent 41a2a01 commit 3047e2d

2 files changed

Lines changed: 21 additions & 0 deletions

File tree

Sources/JSONAPI/Resource/Entity.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,8 +407,19 @@ public extension EntityProxy {
407407
/// allows you to write `entity[\.propertyName]` instead
408408
/// of `entity.relationships.propertyName`.
409409
subscript<T, TFRM: Transformer, U>(_ path: KeyPath<Description.Attributes, TransformedAttribute<T, TFRM>?>) -> U? where TFRM.To == U? {
410+
// Implementation Note: Handles Transform that returns optional
411+
// type.
410412
return attributes[keyPath: path].flatMap { $0.value }
411413
}
414+
415+
/// Access the computed attribute at the given keypath. This just
416+
/// allows you to write `entity[\.propertyName]` instead
417+
/// of `entity.relationships.propertyName`.
418+
subscript<T>(_ path: KeyPath<Description.Attributes, T>) -> T {
419+
// Implementation Note: Handles attributes that are not
420+
// AttributeType. These should only exist as computed properties.
421+
return attributes[keyPath: path]
422+
}
412423
}
413424

414425
// MARK: Relationship Access

Tests/JSONAPITests/Computed Properties/ComputedPropertiesTests.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@ class ComputedPropertiesTests: XCTestCase {
2929
XCTAssertEqual(entity[\.computed], "Sarah2")
3030
}
3131

32+
func test_ComputedNonAttributeAccess() {
33+
let entity = decoded(type: TestType.self, data: computed_property_attribute)
34+
35+
XCTAssertEqual(entity[\.computed2], "Sarah2")
36+
}
37+
3238
func test_ComputedRelationshipAccess() {
3339
let entity = decoded(type: TestType.self, data: computed_property_attribute)
3440

@@ -46,6 +52,10 @@ extension ComputedPropertiesTests {
4652
public var computed: Attribute<String> {
4753
return name.map { $0 + "2" }
4854
}
55+
56+
public var computed2: String {
57+
return computed.value
58+
}
4959
}
5060

5161
public struct Relationships: JSONAPI.Relationships {

0 commit comments

Comments
 (0)