简体   繁体   English

Firebase 交易预订系统

[英]Firebase Transactions Reservations System

I am building a reservation system using firebase.我正在使用 firebase 构建预订系统。 The user can select a number of seats and i want to write them in my document.用户可以 select 多个席位,我想将它们写在我的文档中。 The selected seats are inside an array and they are objects, like so:选定的座位在数组内,它们是对象,如下所示:

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

I want to ensure that no other user could write to the database with at least 1 same seat with transactions.我想确保没有其他用户可以使用至少 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);
});

How can i make the transaction fail if a seat is found in the array of each object inside the document?如果在文档内的每个 object 的数组中找到一个席位,我该如何使交易失败?

You could use array-contains-any for checking if there are any of your seats reserved on the db already and return a sucessful or failing promise depending on the results, also you need to create a reference to an empty document outside the transaction before you can create the document inside it, here is what it could look like:您可以使用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);
});

NOTE : As you can see on the documentation for array-contains-any , this where clause will be limited to 10 values on your reservation.selectedSeats array.注意:正如您在array-contains-any文档中看到的那样,此 where 子句将限制为您的reservation.selectedSeats数组上的 10 个值。 Also I am not sure if you have to use venueId to get the empty document or not, since you want to use that ID, so I encourage you to try both ways.此外,我不确定您是否必须使用venueId来获取空文档,因为您想使用该 ID,所以我鼓励您尝试两种方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM