Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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>
- Loading branch information