The Mauler
The Mauler

Reputation: 148

How to implement Firebase transactions with read operations after write operations

Is there a way to implement read operations after write operations in nodejs for cloud and background functions?

As stated in docs, only server client libraries support transactions with read operations after write operations. But I can't implement one to not trigger error:

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 

I'm using "firebase-admin": "^9.6.0" that uses @google-cloud/firestore "4.5.0" and "firebase-functions": "^3.13.2"

Background function (trigger):

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);
    });
  });

Cloud function (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'] });
  }
};

Upvotes: 0

Views: 277

Answers (1)

The Mauler
The Mauler

Reputation: 148

Docs stated wrong and server libraries doesn't support reads after writes. Documentation will be fixed soon.

From the point of code, there's no way to overcome such situation.

Upvotes: 1

Related Questions