Skip to content

Commit 9a22ec1

Browse files
committed
Fixed encoding to-one relationships
1 parent 8a2896e commit 9a22ec1

2 files changed

Lines changed: 8 additions & 1 deletion

File tree

Sources/CoreModel/Decoder.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,9 @@ internal extension ModelDataDecoder {
137137
func decodeAttribute<T: AttributeDecodable>(_ type: T.Type, forKey key: CodingKey) throws -> T {
138138
log?("Will decode \(type) at path \"\(codingPath.path)\"")
139139
let property = PropertyKey(key)
140+
guard attributes.keys.contains(property) else {
141+
throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Unknown attribute for \"\(key.stringValue)\""))
142+
}
140143
guard let attribute = self.data.attributes[property] else {
141144
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: codingPath, debugDescription: "Cannot decode \(type) for non-existent property \"\(key.stringValue)\""))
142145
}

Sources/CoreModel/Encoder.swift

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,10 @@ internal extension ModelDataEncoder {
9393

9494
func setAttribute(_ value: AttributeValue, forKey key: PropertyKey) throws {
9595
log?("Will set \(value) for attribute \"\(key)\"")
96+
guard relationships.keys.contains(key) == false else {
97+
assertionFailure()
98+
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: "Cannot set attribute value \(value) for relationship \(key)."))
99+
}
96100
guard attributes.keys.contains(key) else {
97101
// TODO: Determine if blacklisted key (e.g. _id)
98102
//throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: "No attribute found for \"\(key)\""))
@@ -124,7 +128,7 @@ internal extension ModelDataEncoder {
124128

125129
func setEncodable <T: Encodable> (_ value: T, forKey key: PropertyKey) throws {
126130

127-
if let encodable = value as? AttributeEncodable {
131+
if let encodable = value as? AttributeEncodable, attributes.keys.contains(key) {
128132
try setAttribute(encodable.attributeValue, forKey: key)
129133
} else {
130134
// encode using Encodable, container should write directly.

0 commit comments

Comments
 (0)