Add encoding to ResourceBody and test it

This commit is contained in:
Mathew Polzin
2018-11-16 18:21:37 -08:00
parent 696e434caa
commit 9802efd917
7 changed files with 114 additions and 94 deletions
+26 -1
View File
@@ -5,7 +5,7 @@
// Created by Mathew Polzin on 11/10/18.
//
public protocol ResourceBody: Decodable {
public protocol ResourceBody: Codable, Equatable {
}
public struct SingleResourceBody<Entity: JSONAPI.EntityType>: ResourceBody {
@@ -20,8 +20,25 @@ public struct ManyResourceBody<Entity: JSONAPI.EntityType>: ResourceBody {
extension SingleResourceBody {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() {
value = nil
return
}
value = try container.decode(Entity.self)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
if value == nil {
try container.encodeNil()
return
}
try container.encode(value)
}
}
extension ManyResourceBody {
@@ -33,4 +50,12 @@ extension ManyResourceBody {
}
values = valueAggregator
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for value in values {
try container.encode(value)
}
}
}