From 3047e2d23a23b0efd511e849704e9037da027307 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Fri, 7 Dec 2018 21:19:08 -0800 Subject: [PATCH] Add access to computed attributes that are not AttributeType --- Sources/JSONAPI/Resource/Entity.swift | 11 +++++++++++ .../Computed Properties/ComputedPropertiesTests.swift | 10 ++++++++++ 2 files changed, 21 insertions(+) diff --git a/Sources/JSONAPI/Resource/Entity.swift b/Sources/JSONAPI/Resource/Entity.swift index c03ec6b..1ab2e8e 100644 --- a/Sources/JSONAPI/Resource/Entity.swift +++ b/Sources/JSONAPI/Resource/Entity.swift @@ -407,8 +407,19 @@ public extension EntityProxy { /// allows you to write `entity[\.propertyName]` instead /// of `entity.relationships.propertyName`. subscript(_ path: KeyPath?>) -> U? where TFRM.To == U? { + // Implementation Note: Handles Transform that returns optional + // type. return attributes[keyPath: path].flatMap { $0.value } } + + /// Access the computed attribute at the given keypath. This just + /// allows you to write `entity[\.propertyName]` instead + /// of `entity.relationships.propertyName`. + subscript(_ path: KeyPath) -> T { + // Implementation Note: Handles attributes that are not + // AttributeType. These should only exist as computed properties. + return attributes[keyPath: path] + } } // MARK: Relationship Access diff --git a/Tests/JSONAPITests/Computed Properties/ComputedPropertiesTests.swift b/Tests/JSONAPITests/Computed Properties/ComputedPropertiesTests.swift index 674cb23..16b7e1f 100644 --- a/Tests/JSONAPITests/Computed Properties/ComputedPropertiesTests.swift +++ b/Tests/JSONAPITests/Computed Properties/ComputedPropertiesTests.swift @@ -29,6 +29,12 @@ class ComputedPropertiesTests: XCTestCase { XCTAssertEqual(entity[\.computed], "Sarah2") } + func test_ComputedNonAttributeAccess() { + let entity = decoded(type: TestType.self, data: computed_property_attribute) + + XCTAssertEqual(entity[\.computed2], "Sarah2") + } + func test_ComputedRelationshipAccess() { let entity = decoded(type: TestType.self, data: computed_property_attribute) @@ -46,6 +52,10 @@ extension ComputedPropertiesTests { public var computed: Attribute { return name.map { $0 + "2" } } + + public var computed2: String { + return computed.value + } } public struct Relationships: JSONAPI.Relationships {