現在、メールアドレスを受け取ってそのメールアドレス分だけFirestoreに書き込みをしようと考えています。
メールアドレスの配列を使ってその配列分だけFor文を回して、Cloud Functionsを呼び出して
そのCloud Functionsの中でFireStoreにデータを書き込もうとしていますが、エラーが出ています。
Swiftから呼び出したフロントのエラーは、INTERNAL
とDEADLINE EXCEEDED
です。
おそらく、FireStoreに対して1秒間の中で2回以上書き込もうとしていてエラーが発生していると思います。
For文で回さなかったらエラーが出ないのですが、 上記の形にするとエラーが出ます。
どうすれば解決できるでしょうか?是非ご教授よろしくお願いいたします。
以下がSwiftのコードです。
func createGroup(members: [String]) {
guard let userId = Auth.auth().currentUser?.uid else { return }
var ref: DocumentReference? = nil
let data =
[
"members": []
] as [String: Any]
ref = COLLECTION_GROUP.addDocument(data: data) {
err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
if !members.isEmpty {
self.provisionNewAccount(members: members)
}
}
}
}
func provisionNewAccount(members: [String]) {
members.forEach { member in
self.functions.httpsCallable("hello").call(["email": member]) { (result, error) in
if let error = error as NSError? {
if error.domain == FunctionsErrorDomain {
let code = FunctionsErrorCode(rawValue: error.code)
let message = error.localizedDescription
let details = error.userInfo[FunctionsErrorDetailsKey]
print(code)
print(message)
print(details)
}
}
print(result?.data)
if let data = (result?.data as? [String: Any]), let text = data["result"] as? String {
print("SUCCESS: \(text)")
}
}
}
}
以下がCloudFunctionsのコードです。
export const hello = functions
.https.onCall(async (data: any, context: any) => {
try {
// New user email
const userEmail = data.email
const fakeDocRef = admin.firestore().collection("_").doc()
const requestId = fakeDocRef.id
// Create the doc in a specific collection
await admin
.firestore()
.collection("usersCreationRequests")
.doc(requestId)
.set({ email: userEmail, treated: false })
return { result: "OK" }
} catch (error) {
console.log(JSON.stringify(error))
throw new functions.https.HttpsError("internal", JSON.stringify(error))
}
})