Using Decodable to get the object and document ID with Firestore

Viewed 1970

I have a simple User class which has the following fields:

{ 
  "localIdentifier": "xyc9870",
  "isOnline": false,
  "username": "ZS"
}

I want to use Swift's Decodable to easily turn the QueryDocumentSnapshot into a type safe Swift struct. I also want to make sure that I get the documentID from theĀ QueryDocumentSnapshot for updating the object later.

This is what I'm currently using to decode but obviously it misses the documentId

struct User: Decodable {

    let localIdentifier: String
    let username: String
    let isOnline: Bool

}

Would love a hand here. Thanks!

1 Answers

I wrote myself a small convenience extension that just brings the documentID into the data JSON and then I can use the simple struct below

extension QueryDocumentSnapshot {

    func prepareForDecoding() -> [String: Any] {
        var data = self.data()
        data["documentId"] = self.documentID

        return data
    }

}

Decode using:

struct User: Decodable {

    let documentId: String
    let localIdentifier: String
    let username: String
    let isOnline: Bool

}

if let user = try? JSONDecoder().decode(User.self, fromJSONObject: doc.prepareForDecoding()) {
    ...
}

Edit:

My JSONDecoder extension

extension JSONDecoder {
    func decode<T>(_ type: T.Type, fromJSONObject object: Any) throws -> T where T: Decodable {
        return try decode(T.self, from: try JSONSerialization.data(withJSONObject: object, options: []))
    }
}
Related