Atomicity in NodeJS API Request

  backend, database, javascript, node.js

I’m currently designing a backend system for an ecommerce platform. I follow a service based approach in my design. However, I came across something that could be an issue. Lets say that I have a Controller which calls 2 services in response to an API Call.

app.get('/', async (req, res, next) => {
  const { orderDetails } = req.body;
  try {
    // Do some validation for orderDetails
    await paymentService.createPayment(orderDetails.payment); // This succeeds
    await orderService.createOrder(orderDetails.cart); // This fails
    // Handle response
  } catch (error) {
    // Handle Error
  }
});

In the above code, Assume that the paymentService succeeds but the orderService fails. This would mean that I will receive payment but the order will not be placed, which is not how the system should work.

My question is, is there a way to make this Atomic? Basically I want both the service to succeed or fail together. Any help would be appreciated. Thanks.

Source: Ask Javascript Questions

LEAVE A COMMENT