firebase FireStore Transaction

本稿について

本稿はサイト運営者が学んだことなどを記したメモの内容です。
全てが正確な情報とは限りません。ご注意ください。また修正するべき点は適時修正していきます

トランザクションを使って複数のデータをinsertする

    // トランザクションを使用してデータを作成する
    let batch  = db.batch()
    iosRef    = db.collection("ios").doc(body["uid"])
    androidRef = db.collection("android").doc(body["uid"])
    webRef    = db.collection("web").doc(body["uid"])
    userRef    = db.collection("user-data").doc(body["uid"])

    batch.set(iosRef, data)
    batch.set(androidRef, data)
    batch.set(webRef, data)
    batch.set(userRef, {
      token:    body["token"],
      createdAt: time,
      updatedAt: time
    })

    batch.commit().then(() => {
      return true
    }).catch((err) => {
      console.error(err)
      // エラーの場合はユーザーデータも削除する
      admin.auth().deleteUser(body["uid"]).then(() => {
        console.warn(`user delete ${body["uid"]}`)
        return true
      }).catch(function(error) {
        // An error happened.
        console.warn("user delete error")
        console.warn(error)
      });
    })


関連ページ

■ firebase

#firebase
Back