簡體   English   中英

Firebase 交易預訂系統

[英]Firebase Transactions Reservations System

我正在使用 firebase 構建預訂系統。 用戶可以 select 多個席位,我想將它們寫在我的文檔中。 選定的座位在數組內,它們是對象,如下所示:

    {
      reservationId: 'id', 
      selectedSeats: [{"x": 0, "y": 0,},
                      {"x": 1, "y": 0,},
                      {"x": 2, "y": 0,}]
    }

我想確保沒有其他用戶可以使用至少 1 個相同的事務席位寫入數據庫。

let transaction = db.runTransaction(t => {
  return t.get(venueId)
    .then(doc => {
      //I need to get all the objects inside the document and check their array of reservations.
      t.set(venueId, {reservation});
    });
}).then(result => {
  console.log('Transaction success!');
}).catch(err => {
  console.log('Transaction failure:', err);
});

如果在文檔內的每個 object 的數組中找到一個席位,我該如何使交易失敗?

您可以使用array-contains-any來檢查數據庫上是否已經保留了任何座位,並根據結果返回成功或失敗的 promise,您還需要在交易之前創建對空文檔的引用可以在其中創建文檔,如下所示:

//reference to a document that still does not exists
var docRef = db.collection(reservation).doc()
let transaction = db.runTransaction(t => {
  return t.get(venueId)
    .then(doc => {
      db.collection('reservation')
        .where('selectedSeats', 'array-contains-any', reservation.selectedSeats)
        .get()
        .then(snapshot =>{
            if (snapshot.empty) {
                t.set(docRef, {
                    uid: venueId,
                    reservation: reservation
                });
                return Promise.resolve('Reservation Complete');
            }
            return Promise.reject('Seats already taken');
        })
    });
}).then(result => {
  console.log('Transaction success!');
}).catch(err => {
  console.log('Transaction failure:', err);
});

注意:正如您在array-contains-any文檔中看到的那樣,此 where 子句將限制為您的reservation.selectedSeats數組上的 10 個值。 此外,我不確定您是否必須使用venueId來獲取空文檔,因為您想使用該 ID,所以我鼓勵您嘗試兩種方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM