Skip to content

Commit b34f9f2

Browse files
authored
Verify that @documentid works with custom Codable methods. (#7247)
Prompted by #7242.
1 parent f9e5be1 commit b34f9f2

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Firestore/Swift/Tests/Integration/CodableIntegrationTests.swift

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,53 @@ class CodableIntegrationTests: FSTIntegrationTestCase {
248248
let decoded = try readDocument(forRef: docToWrite).data(as: Model.self)
249249
XCTAssertEqual(decoded!, Model(name: "name", docId: docToWrite))
250250
}
251+
252+
func testSelfDocumentIDWithCustomCodable() throws {
253+
struct Model: Codable, Equatable {
254+
var name: String
255+
@DocumentID var docId: DocumentReference?
256+
257+
enum CodingKeys: String, CodingKey {
258+
case name
259+
case docId
260+
}
261+
262+
public init(name: String, docId: DocumentReference?) {
263+
self.name = name
264+
self.docId = docId
265+
}
266+
267+
public init(from decoder: Decoder) throws {
268+
let container = try decoder.container(keyedBy: CodingKeys.self)
269+
name = try container.decode(String.self, forKey: .name)
270+
docId = try container.decode(DocumentID<DocumentReference>.self, forKey: .docId)
271+
.wrappedValue
272+
}
273+
274+
public func encode(to encoder: Encoder) throws {
275+
var container = encoder.container(keyedBy: CodingKeys.self)
276+
try container.encode(name, forKey: .name)
277+
// DocumentId should not be encoded when writing to Firestore; it's auto-populated when
278+
// reading.
279+
}
280+
}
281+
282+
let docToWrite = documentRef()
283+
let model = Model(
284+
name: "name",
285+
docId: nil
286+
)
287+
288+
try setData(from: model, forDocument: docToWrite, withFlavor: .docRef)
289+
let data = readDocument(forRef: docToWrite).data()
290+
291+
// "docId" is ignored during encoding
292+
XCTAssertEqual(data! as! [String: String], ["name": "name"])
293+
294+
// Decoded result has "docId" auto-populated.
295+
let decoded = try readDocument(forRef: docToWrite).data(as: Model.self)
296+
XCTAssertEqual(decoded!, Model(name: "name", docId: docToWrite))
297+
}
251298
#endif // swift(>=5.1)
252299

253300
func testSetThenMerge() throws {

0 commit comments

Comments
 (0)