首页 > 解决方案 > 写操作后如何使用读操作实现 Firebase 事务

问题描述

有没有办法在nodejs中为云和后台功能实现写操作后的读操作?

docs中所述,只有服务器客户端库支持在写操作后进行读操作的事务。但我无法实现一个不触发错误:

Error: Firestore transactions require all reads to be executed before all writes.
    at Transaction.get (/workspace/node_modules/@google-cloud/firestore/build/src/transaction.js:76:19)
    at /workspace/lib/firestore/tests-write.js:46:11
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Transaction.runTransaction (/workspace/node_modules/@google-cloud/firestore/build/src/transaction.js:323:26)
    at async /workspace/lib/firestore/tests-write.js:43:5 

我正在使用"firebase-admin": "^9.6.0"那个用途@google-cloud/firestore "4.5.0""firebase-functions": "^3.13.2"

后台功能(触发器):

const onFirestoreTestsWrite = functions.firestore
  .document('tests/{testId}')
  .onWrite(async (change, context) => {
    await admin.firestore().runTransaction(async (t) => {
      const testDoc = await admin.firestore().collection('tests').doc().get();
      t.set(testDoc.ref, {});
      t.get(testDoc.ref);
    });
  });

云功能(http):

const tests_get = async (req, res) => {
  try {
    const test = await admin.firestore().runTransaction(async (t) => {
      const testDoc = await admin.firestore().collection('tests').doc().get();
      t.set(testDoc.ref, {});
      return t.get(testDoc.ref);
    });
    res.send({id: test.id});
  } catch (e) {
    res.status(400).send({ error: e['message'] });
  }
};

标签: node.jstypescriptfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


文档说明错误,服务器库不支持先读后写。文档将很快修复。

从代码的角度来看,没有办法克服这种情况。


推荐阅读