Firestore database transactions not living up to our expectations

When attempting firebase database transactions, they fail without throwing any errors.

Here is the relevant code snippet:

Code:

import * as admin from "firebase-admin";
const db = admin.firestore();

class Doc {
  first = 0;
  second = 0;
  third = 0;
  id = Math.random();
  constructor(data: any) {
    if (data) Object.assign(this, data);
    this.first += 1;
    this.second += 2;
    this.third += 3;
    console.log(this);
  }
  serialize() {
    return {
      first: this.first,
      second: this.second,
      third: this.third,
      id: this.id,
    };
  }
}

export function runSingleTransaction() {
  return db
    .runTransaction(async (transaction) => {
      const docSnapshot = await db
        .collection("transaction-test")
        .doc("base-test")
        .get();
      let doc = docSnapshot.data();
      const writeDoc = new Doc(doc);
      if (doc) transaction.update(docSnapshot.ref, writeDoc.serialize());
      else transaction.set(docSnapshot.ref, writeDoc.serialize());
      return writeDoc;
    }, {})
    .then((wd) => {
      console.log("the transaction passed");
      return wd;
    })
    .catch((err) => {
      console.log("the transaction failed");
      return err;
    });
}

Index:

import * as functions from "firebase-functions";
import {runSingleTransaction } from "./entrypoints";

export const runTransaction = functions.https.onRequest(
  async (request, response) => {
    response.set("Access-Control-Allow-Origin", "*");
    const i = await runSingleTransaction();
    response.status(200).send(JSON.stringify({ res: i }));
  }
);

Test:

  it.only("should run db transactions in practice", async () => {
    const ret = [];
    for (let i = 0; i < 10; i++) {
      const res = axios.get(
        "http://localhost:5001/guestfeedback-2f0f8/us-central1/runTransaction"
      );
      ret.push(res);
    }
    await Promise.all(ret);
  });

The output can be viewed here: https://i.sstatic.net/Lkzzd.jpg https://i.sstatic.net/bCH76.jpg

Expected Behavior: In Firestore, we expect to see an increment of 10, with the first property being 10, the second being 20, and the third being 30. Logically, we anticipate failure and retry logs multiple times due to concurrent writes, but all logs are passing smoothly.

Is this the optimal way to handle concurrency? If so, what am I overlooking? If not, how should this use case be properly handled?

Answer №1

Oops! I made a mistake in my code, the correct version should look like this:

(transaction) => {
  ...
  const docRef = db
          .collection("transaction-test")
          .doc("base-test");
  const docSnapshot = transaction.get(docRef);
  ...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on obtaining the total value from a JSON Array in Angular 2 using TypeScript

I received a JSON response which includes carts values with different amounts. "carts": { "value": [ { "Amt": 40 }, { "Amt": 20.25 }, ...

Module 'next-intl/client' cannot be located

When I run npm test, I encounter the following error: 'next-intl/client' module not found jest.mock( | ^ 22 | 'next-intl/client', 23 | (): Record<string, unknown> => ({ 24 | usePathname: ...

Leveraging the power of both TypeScript 2.3 and 2.4 concurrently within Visual Studio 2015.3 on a single machine

Can TS 2.3 and TS 2.4 be used on the same machine simultaneously? For example, I have one project in VS 2015.3 compiling with TS 2.3 and another project compiling with the latest TypeScript version (TS 2.4). I recently installed TypeScript 2.4, which aut ...

Images are failing to load in Ionic 3

Currently working on developing an Ionic application and troubleshooting the use of the camera native plugin. The script functions flawlessly in a fresh project, but encounters issues within the current project environment. Initially suspected a problem w ...

The quantity of documents queried does not align with the number of data counts retrieved from Firestore

Facing an issue with calculating the Firestore read count as it keeps increasing rapidly even with only around 15 user documents. The count surges by 100 with each page reload and sometimes increases on its own without any action from me. Could this be due ...

The error "Cannot access property afs (Angularfirestore) of undefined in the collection.set()" occurred

In the current code snippet below, I am iterating over a collection of data and updating a field if the email matches. The issue arises when trying to set new values where it crashes. The iteration process itself functions correctly, with afs being Angular ...

Challenges in designing components in Angular 2.0 and beyond

Issue at hand - There are two input controls on the same page, each belonging to separate components. When a value is entered into the first input box, it calculates the square value and updates the second input control accordingly. Conversely, if the v ...

Display the initial MUI components from an array of data in a distinctive manner

Trying to display the content of an Accordion by passing props down through a list array to a component. I have identified the issue but unsure how to call the component and pass the props differently. Below is the code snippet. Code for the parent compon ...

Bringing Typescript classes into React-scripts does not act as a constructor

I am currently working on integrating a Typescript file into my existing app using Yarn and React-scripts. Encountered error: Module not found, unable to resolve './DiamondNodeModel' import {DiamondNodeModel} from './DiamondNodeModel&ap ...

Adding a fresh element to an array in Angular 4 using an observable

I am currently working on a page that showcases a list of locations, with the ability to click on each location and display the corresponding assets. Here is how I have structured the template: <li *ngFor="let location of locations" (click)="se ...

Obtain keys from an object implemented with an interface in TypeScript

Is it possible to retrieve the actual keys of an object when utilizing an interface to define the object? For example: interface IPerson { name: string; } interface IAddress { [key: string]: IPerson; } const personInAddressObj: IAddress= { so ...

OpenTok Angular 6 encountered an error with code TS2314 stating that the generic type 'Promise<T>' needs to have 1 type argument specified

Issue in opentok.d.ts File: Error TS2314 npm version: 6.2.0 node: v8.10.0 Angular CLI: 6.2.3 Operating System: Linux x64 Angular Version: 7.0.0-beta.5 @opentok/client": "^2.14.8 ...

encountering the issue of not being able to assign a parameter of type 'string | undefined' to a parameter of type

Seeking help with the following issue: "Argument of type 'string | undefined' is not assignable to parameter of type" I am unsure how to resolve this error. Here is the section of code where it occurs: export interface IDropDown { l ...

What is the process for generating an index.d.ts file within a yarn package?

I'm facing an issue with creating the index.d.ts file for my yarn package. Here is my configuration in tsconfig.json: { "include": ["src/**/*"], "exclude": ["node_modules", "**/*.spec.ts"], " ...

What is the best way to implement a switch case for the value of a property within an object in a TypeScript file?

The object I'm dealing with looks like this: {a: auth?.type === '1' || auth?.type === '2' || auth?.type === '3' ? { reason: // I need to implement a switch case here : un ...

Using TypeScript, creating a tagged template literal for running Jest tests with the `test.each`

Struggling to construct a jest test.each with a tagged template literal test.each` height | text ${10} | ${undefined} ${20} | ${undefined} ${10} | ${'text'} ${20} | ${'text'} `('$height and $text behave as expected&a ...

Issue with firing Facebook pixel after router.push() in Next.js

Within this code block is FB pixel tracking code <Script id="some-id" strategy="afterInteractive">some fb pixel code</Script> The issue arises when navigating to a page containing the script using router.push(SOME_ROUTE). T ...

What is the best way to iterate through all class properties that are specified using class-validator?

I have a class defined using the class-validator package. class Shape { @IsString() value?: string @IsString() id?: string } I am trying to find a way to retrieve the properties and types specified in this class. Is there a method to do s ...

Can anyone assist me with creating a custom sorting pipe in Angular 2?

*ngFor="let match of virtual | groupby : 'gameid' I have this code snippet that uses a pipe to group by the 'gameid' field, which consists of numbers like 23342341. Now, I need help sorting this array in ascending order based on the g ...

Are you struggling with perplexing TypeScript error messages caused by a hyphen in the package name?

After creating a JavaScript/TypeScript library, my goal is for it to function as: A global variable when called from either JavaScript or TypeScript Accessible via RequireJS when called from either JavaScript or TypeScript Complete unit test coverage Th ...