Skip to content

Commit

Permalink
Verify that @documentid works with custom Codable methods.
Browse files Browse the repository at this point in the history
Prompted by #7242.
  • Loading branch information
wilhuff committed Jan 5, 2021
1 parent e09c321 commit 15690e6
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions Firestore/Swift/Tests/Integration/CodableIntegrationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,53 @@ class CodableIntegrationTests: FSTIntegrationTestCase {
let decoded = try readDocument(forRef: docToWrite).data(as: Model.self)
XCTAssertEqual(decoded!, Model(name: "name", docId: docToWrite))
}

func testSelfDocumentIDWithCustomCodable() throws {
struct Model: Codable, Equatable {
var name: String
@DocumentID var docId: DocumentReference?

enum CodingKeys: String, CodingKey {
case name
case docId
}

public init(name: String, docId: DocumentReference?) {
self.name = name
self.docId = docId
}

public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let name = try container.decode(String.self, forKey: .name)
let docId = try container.decode(DocumentID<DocumentReference>.self, forKey: .docId)
self.init(name: name, docId: docId.wrappedValue)
}

public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
// DocumentId should not be encoded when writing to Firestore; it's auto-populated when
// reading.
}
}

let docToWrite = documentRef()
let model = Model(
name: "name",
docId: nil
)

try setData(from: model, forDocument: docToWrite, withFlavor: .docRef)
let data = readDocument(forRef: docToWrite).data()

// "docId" is ignored during encoding
XCTAssertEqual(data! as! [String: String], ["name": "name"])

// Decoded result has "docId" auto-populated.
let decoded = try readDocument(forRef: docToWrite).data(as: Model.self)
XCTAssertEqual(decoded!, Model(name: "name", docId: docToWrite))
}
#endif // swift(>=5.1)

func testSetThenMerge() throws {
Expand Down

0 comments on commit 15690e6

Please sign in to comment.