Skip to content

Instantly share code, notes, and snippets.

@perpeer
Created December 4, 2022 14:19
Show Gist options
  • Select an option

  • Save perpeer/c44a2eb149c30b70d1bfc57f66c7436f to your computer and use it in GitHub Desktop.

Select an option

Save perpeer/c44a2eb149c30b70d1bfc57f66c7436f to your computer and use it in GitHub Desktop.
Swift Firebase Store Importer
import FirebaseFirestore
import FirebaseFirestoreSwift
struct FirebaseStoreImporter {
private let firestore: Firestore
init() {
self.firestore = Firestore.firestore()
}
func send<T: Codable>(_ type: T.Type, json: String, collection: String) {
guard let parsedModel: [T] = parse(json: json) else {
print("Failed to parse...")
return
}
write(documents: parsedModel, in: collection)
}
private func parse<T: Codable>(json: String) -> [T]? {
guard let jData = json.data(using: .utf8) else {
print("Failed to convert json string to data...")
return nil
}
guard let model = try? JSONDecoder().decode([T].self, from: jData) else {
print("Failed to decode json data...")
return nil
}
return model
}
private func write(documents models: [some Codable], in collection: String) {
let collectionRef = firestore.collection(collection)
do {
try models.forEach { model in
let document = try collectionRef.addDocument(from: model)
print("Document writed with ref: \(document), id:\(document.documentID)")
}
} catch {
print("Failed to write documents in \(collection): ", error.localizedDescription)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment