firebase实时数据库标准交易与自定义交易

时间:2019-10-20 17:52:59

标签: javascript firebase firebase-realtime-database transactions

我想知道是否可以使用自定义交易而不是标准交易。使用第二种方法是否存在数据损坏问题?

例如,如果我的计数器为0,并且两个人同时将其增加为1,是计数器损坏还是请求排队并在以后执行?

规则

".write": "data.val() == null && newData.val() == 1 || newData.val() == data.val() + 1"

标准交易

const db = firebaseApp.database();
const ref = db.ref().child('node/counter');

ref.transaction(count => {
    if (count === null) {
        return count = 1
    } else {
        return count + 1
    }
});

自定义交易

const customTransaction = async (retry = 10) => {
  const db = firebaseApp.database();
  const ref = db.ref().child('node/counter');

  for (let i = 0; i < retry; i++) {
    try {
      const snapshot = await ref.once('value');
      const counter = snapshot.val() ? snapshot.val() : 0;

      await ref.set(counter + 1);

      return counter + 1;
    } catch (e) {
      if(i >= retry - 1) {
        throw new Error(e);
      }
    }
  }
}

try {
  await customTransaction(20);
} catch (e) {
  console.log(e);
}

具有多个计数器的自定义

const customTransaction = async (retry = 10) => {
  const db = firebaseApp.database();
  const ref = db.ref().child('node/');

  for (let i = 0; i < retry; i++) {
    try {
      const snap = await ref.child('counter').once('value');
      const snap1 = await ref.child('counter1').once('value');
      const snap2 = await ref.child('counter2').once('value');


      const counter = snap.val() ? snap.val() : 0;
      const counter1 = snap1.val() ? snap1.val() : 0;
      const counter2 = snap2.val() ? snap2.val() : 0;

      const paths = {};
      paths['node/counter'] = counter + 1;
      paths['node/counter1'] = counter1 + 1;
      paths['node/counter2'] = counter2 + 1;

      await db.ref().update(paths);

      return {
        counter: counter + 1,
        counter1: counter1 + 1,
        counter2: counter2 + 1
      }
    } catch (e) {
      if(i >= retry - 1) {
        throw new Error(e);
      }
    }
  }
}

try {
  await customTransaction(20);
} catch (e) {
  console.log(e);
}

0 个答案:

没有答案