mirror of
https://github.com/caoer/CodableFirebase.git
synced 2026-06-11 15:42:41 +08:00
Compare commits
27 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1384814716 | ||
|
|
b0e86866a0 | ||
|
|
0c60f70d91 | ||
|
|
df9dfe1dda | ||
|
|
2afa8c101c | ||
|
|
ec22c1649e | ||
|
|
8279c70901 | ||
|
|
c4ed0ec8eb | ||
|
|
fcfb7b8b1e | ||
|
|
747d540d77 | ||
|
|
e6947deb6b | ||
|
|
eaf809498a | ||
|
|
3a08c9e650 | ||
|
|
4cfd13702b | ||
|
|
3c61d54654 | ||
|
|
2528453f9b | ||
|
|
587db265cd | ||
|
|
04facd2f6d | ||
|
|
f3eed29a7d | ||
|
|
7aff81a267 | ||
|
|
9fa47dd610 | ||
|
|
31ecb57f14 | ||
|
|
6a6fcc1d07 | ||
|
|
02cd074714 | ||
|
|
69d0a835be | ||
|
|
e0b61e57e5 | ||
|
|
e32bd8f4d6 |
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "CodableFirebase"
|
||||
s.version = "0.0.3"
|
||||
s.version = "0.0.6"
|
||||
s.summary = "Use Codable with Firebase"
|
||||
s.description = "This library helps you use your custom models that conform to Codable protocol with Firebase Realtime Database and Firestore"
|
||||
s.homepage = "https://github.com/alickbass/CodableFirebase"
|
||||
|
||||
@@ -13,6 +13,7 @@ class _FirebaseDecoder : Decoder {
|
||||
struct _Options {
|
||||
let dateDecodingStrategy: FirebaseDecoder.DateDecodingStrategy?
|
||||
let dataDecodingStrategy: FirebaseDecoder.DataDecodingStrategy?
|
||||
let skipFirestoreTypes: Bool
|
||||
let userInfo: [CodingUserInfoKey : Any]
|
||||
}
|
||||
|
||||
@@ -1229,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.skipFirestoreTypes && (T.self is FirestoreDecodable.Type) {
|
||||
decoded = value as! T
|
||||
} else {
|
||||
self.storage.push(container: value)
|
||||
decoded = try T(from: self)
|
||||
|
||||
@@ -13,6 +13,7 @@ class _FirebaseEncoder : Encoder {
|
||||
struct _Options {
|
||||
let dateEncodingStrategy: FirebaseEncoder.DateEncodingStrategy?
|
||||
let dataEncodingStrategy: FirebaseEncoder.DataEncodingStrategy?
|
||||
let skipFirestoreTypes: Bool
|
||||
let userInfo: [CodingUserInfoKey : Any]
|
||||
}
|
||||
|
||||
@@ -382,6 +383,13 @@ extension _FirebaseEncoder {
|
||||
return try self.box((value as! Data))
|
||||
} else if T.self == URL.self || T.self == NSURL.self {
|
||||
return self.box((value as! URL).absoluteString)
|
||||
} else if T.self == Decimal.self || T.self == NSDecimalNumber.self {
|
||||
return (value as! NSDecimalNumber)
|
||||
} else if options.skipFirestoreTypes && (value is FirestoreEncodable) {
|
||||
guard let value = value as? NSObject else {
|
||||
throw DocumentReferenceError.typeIsNotNSObject
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// The value should request a container from the _FirebaseEncoder.
|
||||
|
||||
@@ -53,6 +53,7 @@ open class FirebaseDecoder {
|
||||
let options = _FirebaseDecoder._Options(
|
||||
dateDecodingStrategy: dateDecodingStrategy,
|
||||
dataDecodingStrategy: dataDecodingStrategy,
|
||||
skipFirestoreTypes: false,
|
||||
userInfo: userInfo
|
||||
)
|
||||
let decoder = _FirebaseDecoder(referencing: container, options: options)
|
||||
|
||||
@@ -57,6 +57,7 @@ open class FirebaseEncoder {
|
||||
let options = _FirebaseEncoder._Options(
|
||||
dateEncodingStrategy: dateEncodingStrategy,
|
||||
dataEncodingStrategy: dataEncodingStrategy,
|
||||
skipFirestoreTypes: false,
|
||||
userInfo: userInfo
|
||||
)
|
||||
let encoder = _FirebaseEncoder(options: options)
|
||||
|
||||
@@ -8,13 +8,30 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
public protocol FirestoreDecodable: Decodable {}
|
||||
public protocol FirestoreEncodable: Encodable {}
|
||||
|
||||
public typealias DocumentReferenceType = FirestoreDecodable & FirestoreEncodable
|
||||
public typealias FieldValueType = FirestoreEncodable
|
||||
|
||||
public protocol GeoPointType: FirestoreDecodable, FirestoreEncodable {
|
||||
var latitude: Double { get }
|
||||
var longitude: Double { get }
|
||||
init(latitude: Double, longitude: Double)
|
||||
}
|
||||
|
||||
open class FirestoreDecoder {
|
||||
public init() {}
|
||||
|
||||
open var userInfo: [CodingUserInfoKey : Any] = [:]
|
||||
|
||||
open func decode<T : Decodable>(_ type: T.Type, from container: [String: Any]) throws -> T {
|
||||
let options = _FirebaseDecoder._Options(dateDecodingStrategy: nil, dataDecodingStrategy: nil, userInfo: userInfo)
|
||||
let options = _FirebaseDecoder._Options(
|
||||
dateDecodingStrategy: nil,
|
||||
dataDecodingStrategy: nil,
|
||||
skipFirestoreTypes: true,
|
||||
userInfo: userInfo
|
||||
)
|
||||
let decoder = _FirebaseDecoder(referencing: container, options: options)
|
||||
guard let value = try decoder.unbox(container, as: T.self) else {
|
||||
throw DecodingError.valueNotFound(T.self, DecodingError.Context(codingPath: [], debugDescription: "The given dictionary was invalid"))
|
||||
@@ -23,3 +40,39 @@ 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
|
||||
case typeIsNotNSObject
|
||||
}
|
||||
|
||||
extension FirestoreDecodable {
|
||||
public init(from decoder: Decoder) throws {
|
||||
throw DocumentReferenceError.typeIsNotSupported
|
||||
}
|
||||
}
|
||||
|
||||
extension FirestoreEncodable {
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
throw DocumentReferenceError.typeIsNotSupported
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,12 @@ open class FirestoreEncoder {
|
||||
}
|
||||
|
||||
internal func encodeToTopLevelContainer<Value : Encodable>(_ value: Value) throws -> Any {
|
||||
let options = _FirebaseEncoder._Options(dateEncodingStrategy: nil, dataEncodingStrategy: nil, userInfo: userInfo)
|
||||
let options = _FirebaseEncoder._Options(
|
||||
dateEncodingStrategy: nil,
|
||||
dataEncodingStrategy: nil,
|
||||
skipFirestoreTypes: true,
|
||||
userInfo: userInfo
|
||||
)
|
||||
let encoder = _FirebaseEncoder(options: options)
|
||||
guard let topLevel = try encoder.box_(value) else {
|
||||
throw EncodingError.invalidValue(value,
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.0.3</string>
|
||||
<string>0.0.6</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$(CURRENT_PROJECT_VERSION)</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
|
||||
@@ -369,6 +369,19 @@ class TestCodableFirebase: XCTestCase {
|
||||
_testRoundTrip(of: 3 as Double)
|
||||
}
|
||||
|
||||
// MARK: - GeoPoint
|
||||
func testEncodingGeoPoint() {
|
||||
let point = Point(latitude: 2, longitude: 2)
|
||||
XCTAssertEqual((try? FirebaseEncoder().encode(point)) as? NSDictionary, ["latitude": 2, "longitude": 2])
|
||||
XCTAssertEqual(try? FirebaseDecoder().decode(Point.self, from: ["latitude": 2, "longitude": 2]), point)
|
||||
}
|
||||
|
||||
// MARK: - Document Reference
|
||||
func testEncodingDocumentReference() {
|
||||
XCTAssertThrowsError(try FirebaseEncoder().encode(DocumentReference()))
|
||||
XCTAssertThrowsError(try FirebaseDecoder().decode(DocumentReference.self, from: []))
|
||||
}
|
||||
|
||||
// MARK: - Helper Functions
|
||||
private var _emptyDictionary: [String: Any] = [:]
|
||||
|
||||
@@ -415,6 +428,19 @@ class TestCodableFirebase: XCTestCase {
|
||||
// MARK: - Test Types
|
||||
/* FIXME: Import from %S/Inputs/Coding/SharedTypes.swift somehow. */
|
||||
|
||||
// MARK: - GeoPoint
|
||||
struct Point: GeoPointType, Equatable {
|
||||
let latitude: Double
|
||||
let longitude: Double
|
||||
|
||||
static func == (lhs: Point, rhs: Point) -> Bool {
|
||||
return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ReferenceType
|
||||
fileprivate struct DocumentReference: DocumentReferenceType {}
|
||||
|
||||
// MARK: - Empty Types
|
||||
fileprivate struct EmptyStruct : Codable, Equatable {
|
||||
static func ==(_ lhs: EmptyStruct, _ rhs: EmptyStruct) -> Bool {
|
||||
|
||||
@@ -109,6 +109,26 @@ class TestCodableFirestore: XCTestCase {
|
||||
_testRoundTrip(of: TopLevelWrapper(date), expected: ["value": date])
|
||||
}
|
||||
|
||||
func testDecimalValue() {
|
||||
let value = Decimal(2)
|
||||
_testRoundTrip(of: TopLevelWrapper(value), expected: ["value": value])
|
||||
}
|
||||
|
||||
// MARK: - GeoPoint & Document Reference
|
||||
func testEncodingGeoPoint() {
|
||||
let point = GeoPoint(latitude: 2, longitude: 2)
|
||||
let wrapper = TopLevelWrapper(point)
|
||||
XCTAssertEqual((try? FirestoreEncoder().encode(wrapper)) as NSDictionary?, ["value": point])
|
||||
XCTAssertEqual(try? FirestoreDecoder().decode(TopLevelWrapper<GeoPoint>.self, from: ["value": point]), wrapper)
|
||||
XCTAssertThrowsError(try FirestoreEncoder().encode(TopLevelWrapper(Point(latitude: 2, longitude: 2))))
|
||||
}
|
||||
|
||||
func testEncodingDocumentReference() {
|
||||
let val = TopLevelWrapper(DocumentReference())
|
||||
XCTAssertEqual((try? FirestoreEncoder().encode(val)) as NSDictionary?, ["value": val.value])
|
||||
XCTAssertEqual(try? FirestoreDecoder().decode(TopLevelWrapper<DocumentReference>.self, from: ["value": val.value]), val)
|
||||
}
|
||||
|
||||
private func _testEncodeFailure<T : Encodable>(of value: T) {
|
||||
do {
|
||||
let _ = try FirestoreEncoder().encode(value)
|
||||
@@ -164,3 +184,21 @@ func expectEqualPaths(_ lhs: [CodingKey], _ rhs: [CodingKey], _ prefix: String)
|
||||
XCTAssertEqual(key1.stringValue, key2.stringValue, "\(prefix) CodingKey.stringValue mismatch: \(type(of: key1))('\(key1.stringValue)') != \(type(of: key2))('\(key2.stringValue)')")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeioPoint
|
||||
fileprivate class GeoPoint: NSObject, GeoPointType {
|
||||
let latitude: Double
|
||||
let longitude: Double
|
||||
|
||||
required init(latitude: Double, longitude: Double) {
|
||||
self.latitude = latitude
|
||||
self.longitude = longitude
|
||||
}
|
||||
|
||||
static func == (lhs: Point, rhs: Point) -> Bool {
|
||||
return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ReferenceType
|
||||
fileprivate class DocumentReference: NSObject, DocumentReferenceType {}
|
||||
|
||||
48
README.md
48
README.md
@@ -1,16 +1,20 @@
|
||||
# CodableFirebase
|
||||
Use [Codable](https://developer.apple.com/documentation/swift/codable) with [Firebase](https://firebase.google.com)
|
||||
|
||||
[](https://github.com/alickbass/CodableFirebase)
|
||||
[](https://github.com/Carthage/Carthage)
|
||||
[](https://travis-ci.org/alickbass/CodableFirebase)
|
||||
[](https://codecov.io/gh/alickbass/CodableFirebase)
|
||||
|
||||
## Overview
|
||||
|
||||
This library helps you to use your custom type that conform to `Codable` protocol with Firebase. Here's an example of model:
|
||||
This library helps you to use your custom types that conform to `Codable` protocol with Firebase. Here's an example of a custom model:
|
||||
|
||||
```swift
|
||||
struct Model: Codable {
|
||||
enum MyEnum: Int, Codable {
|
||||
case one, two, three
|
||||
}
|
||||
|
||||
let stringExample: String
|
||||
let booleanExample: Bool
|
||||
let numberExample: Double
|
||||
@@ -18,6 +22,7 @@ struct Model: Codable {
|
||||
let arrayExample: [String]
|
||||
let nullExample: Int?
|
||||
let objectExample: [String: String]
|
||||
let myEnum: MyEnum
|
||||
}
|
||||
```
|
||||
|
||||
@@ -80,3 +85,42 @@ Firestore.firestore().collection("data").document("one").getDocument { (document
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### How to use `GeoPoint`, `DocumentRefence`, `FieldValue` in Firestore
|
||||
|
||||
In order to use these 2 types with `Firestore`, you need to add the following code somewhere in your app:
|
||||
|
||||
```swift
|
||||
extension DocumentReference: DocumentReferenceType {}
|
||||
extension GeoPoint: GeoPointType {}
|
||||
extension FieldValue: FieldValueType {}
|
||||
```
|
||||
|
||||
and now they become `Codable` and can be used properly with `FirestoreEncoder` and `FirestoreDecoder`.
|
||||
|
||||
***PLEASE NOTE*** that as `FieldValue` is only used to [`setData()` and `updateData()`](https://firebase.google.com/docs/reference/swift/firebasefirestore/api/reference/Classes/FieldValue), it only adopts the `Encodable` protocol.
|
||||
|
||||
## Integration
|
||||
|
||||
### CocoaPods (iOS 9+)
|
||||
|
||||
You can use CocoaPods to install CodableFirebase by adding it to your Podfile:
|
||||
|
||||
```swift
|
||||
platform :ios, '9.0'
|
||||
use_frameworks!
|
||||
|
||||
target 'MyApp' do
|
||||
pod 'CodableFirebase'
|
||||
end
|
||||
```
|
||||
|
||||
Note that this requires CocoaPods version 36, and your iOS deployment target to be at least 9.0:
|
||||
|
||||
### Carthage (iOS 9+)
|
||||
|
||||
You can use Carthage to install CodableFirebase by adding it to your Cartfile:
|
||||
|
||||
```swift
|
||||
github "alickbass/CodableFirebase"
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user