From 7aff81a267fad97cb22cb5e8f0309616b08e87a7 Mon Sep 17 00:00:00 2001 From: Oleksii Dykan Date: Thu, 25 Jan 2018 17:14:11 +0100 Subject: [PATCH] Add geopointtype and documentreference protocols --- CodableFirebase/Decoder.swift | 2 ++ CodableFirebase/FirestoreDecoder.swift | 41 ++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/CodableFirebase/Decoder.swift b/CodableFirebase/Decoder.swift index 4ca29fa..6e66198 100644 --- a/CodableFirebase/Decoder.swift +++ b/CodableFirebase/Decoder.swift @@ -1230,6 +1230,8 @@ extension _FirebaseDecoder { } else if T.self == Decimal.self || T.self == NSDecimalNumber.self { guard let decimal = try self.unbox(value, as: Decimal.self) else { return nil } decoded = decimal as! T + } else if options.skipGeoPointAndReference && (T.self is GeoPointType || T.self is DocumentReferenceType) { + decoded = value as! T } else { self.storage.push(container: value) decoded = try T(from: self) diff --git a/CodableFirebase/FirestoreDecoder.swift b/CodableFirebase/FirestoreDecoder.swift index a647e77..40ffb7c 100644 --- a/CodableFirebase/FirestoreDecoder.swift +++ b/CodableFirebase/FirestoreDecoder.swift @@ -8,6 +8,14 @@ import Foundation +protocol GeoPointType: Codable { + var latitude: Double { get } + var longitude: Double { get } + init(latitude: Double, longitude: Double) +} + +protocol DocumentReferenceType: Codable {} + open class FirestoreDecoder { public init() {} @@ -28,3 +36,36 @@ open class FirestoreDecoder { return value } } + +enum GeoPointKeys: CodingKey { + case latitude, longitude +} + +extension GeoPointType { + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: GeoPointKeys.self) + let latitude = try container.decode(Double.self, forKey: .latitude) + let longitude = try container.decode(Double.self, forKey: .longitude) + self.init(latitude: latitude, longitude: longitude) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: GeoPointKeys.self) + try container.encode(latitude, forKey: .latitude) + try container.encode(longitude, forKey: .longitude) + } +} + +enum DocumentReferenceError: Error { + case typeIsNotSupported +} + +extension DocumentReferenceType { + public init(from decoder: Decoder) throws { + throw DocumentReferenceError.typeIsNotSupported + } + + public func encode(to encoder: Encoder) throws { + throw DocumentReferenceError.typeIsNotSupported + } +}