@@ -248,6 +248,53 @@ class CodableIntegrationTests: FSTIntegrationTestCase {
248
248
let decoded = try readDocument ( forRef: docToWrite) . data ( as: Model . self)
249
249
XCTAssertEqual ( decoded!, Model ( name: " name " , docId: docToWrite) )
250
250
}
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
+ }
251
298
#endif // swift(>=5.1)
252
299
253
300
func testSetThenMerge( ) throws {
0 commit comments