tHatpart
tHatpart

Reputation: 1136

Swift Async/Await with Firebase Realtime Database

I am trying to write a simple database query to fetch some data from my realtime database, I wanted to use Async/Await but I don't know if it's possible with observeSingleEvent

Is it possible to do something like this?

func getPromoCodes() async throws -> [PromoCode] {
    promoCodes.observeSingleEvent(of: .value) { snap in
        guard let snap = snap.value as? [String: Any] else {
            return []
        }
        
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: snap)
            let decoded = try JSONDecoder().decode([PromoCode].self, from: jsonData)
                        
            return decoded
        } catch {
            return []
        }
    }
}

Upvotes: 1

Views: 664

Answers (2)

lburgo
lburgo

Reputation: 9

 func add(company: Company) async -> Result<Company, Error> {
    do {
        let company = try await collection_company.addDocument(from: company).getDocument().data(as: Company.self)
        return .success(company)
    } catch {
        return .failure(error)
    }
}

func retrieve(id: String) async -> Result<[Company], Error> {
    do {
        let snapshot = try await collection_company.whereField("owner", isEqualTo: id).getDocuments()
        let documents = snapshot.documents
        return .success(documents.compactMap({ try? $0.data(as: Company.self) }))
    } catch {
        return .failure(error)
    }
}

func update(company: Company) async {
    guard let id = company.id else { return }
    do {
        try collection_company.document(id).setData(from: company)
    } catch {
        print(error.localizedDescription)
    }
}

func delete(company: Company) async {
    do {
        guard let id = company.id else { return }
        try await collection_company.document(id).delete()
    }
    catch {
        print(error.localizedDescription)
    }
}

Upvotes: 0

tHatpart
tHatpart

Reputation: 1136

Turns out it's pretty simple, each DatabaseReference has an async getData function

func getPromoCodes() async throws -> [PromoCode] {
    let data = try await promoCodes.getData()
    
    print("DATA HERE: \(data)")
    
    guard let data = data.value as? [String: Any] else {
        return []
    }
    
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: data)
        let decoded = try JSONDecoder().decode([String: PromoCode].self, from: jsonData)
                    
        return decoded.map({ $0.value })
    } catch {
        print("DECODE: \(error)")
        return []
    }
}

Upvotes: 2

Related Questions