Files
medusa-store/packages
Sebastian Rindom 1b99c5dc22 fix(medusa): ensure transaction is reused when service calls itself (#6089)
**What**
- ProductService.create calls ProductService.retrieve before returning. This fix ensures that the manager created in the atomicPhase is used when ProductService.retrieve is called.

**Why**
- Without the explicit use of the same manager in the retrieve call, race conditions easily occur if you have concurrent ProductService.create calls. The code below can reproduce the scenario:
```javascript
  const productData = [
    {
      barcode: `1234233423-${Math.random() * 100}`,
      external_id: `1234233423-${Math.random() * 100}`,
      description: "super cool product",
      discountable: true,
      hs_code: "1234213",
      origin_country: "DK",
      title: `Super cool product ${Math.random() * 100}`,
      type: { value: "Eyewear" },
      sales_channels: [{ id: sc.id }],
    },
    {
      barcode: `1234233423-${Math.random() * 100}`,
      external_id: `random-external-id-${Math.random() * 100}`,
      description: "super cool product",
      discountable: true,
      hs_code: "1234213",
      origin_country: "DK",
      title: `Super cool product ${Math.random() * 100}`,
      type: { value: "Eyewear" },
      sales_channels: [{ id: sc.id }],
    },
  ];

  const result = await Promise.all(
    productData.map(async (product) => productService.create(product))
  );
```

**Explaination**

What happens is the following:

- Request 1 calls `ProductService.create`. This in turn calls `atomicPhase` which sets the `ProductService.transactionManager_ = txForReqOne`
- Request 1 creates the product in the DB with `txForReqOne`.
- Request 2 calls `ProductService.create`. This in turn calls `atomicPhase` which sets the `ProductService.transactionManager_ = txForReqTwo`
- Request 1 reaches the end of `ProductService.create` where `this.retrieve` is called. Because the ProductService is a singleton the retrieve call will attempt to use `txForReqTwo` to fetch the product. 
- **Error**: since `txForReqTwo` can't read the data of `txForReqOne`, the product is not found.



Co-authored-by: Oli Juhl <59018053+olivermrbl@users.noreply.github.com>
2024-01-19 11:03:17 +00:00
..
2024-01-09 18:41:35 +01:00
2024-01-09 18:41:35 +01:00
2024-01-18 15:50:56 +01:00