docs: general fixes and overall changes (#7258)

* editing halfway

* edited second half

* adjust starter steps

* fix build

* typo fix
This commit is contained in:
Shahed Nasser
2024-05-07 18:00:28 +02:00
committed by GitHub
parent 8db62827ac
commit 327e446974
57 changed files with 872 additions and 1849 deletions
@@ -0,0 +1,71 @@
export const metadata = {
title: `${pageNumber} Transactions in Services`,
}
# {metadata.title}
In this chapter, youll learn about transactions and how to use them in a service.
## What is a Transaction?
A transaction wraps a set of operations to ensure that when an error occurs, all database changes made by the executed operations are rolled back.
For example, if you have a service with a method that updates data of your custom data model, you can wrap the methods operations in a transaction. Then, if an error occurs during the method's execution, the data update in the database is rolled back.
---
## How to Use Transactions?
To use transactions, change your service class to extend the `TransactionBaseService` imported from `@medusajs/medusa`:
```ts title="src/services/hello-world.ts" highlights={[["8"]]}
import { TransactionBaseService } from "@medusajs/medusa"
import { IProductModuleService } from "@medusajs/types"
type InjectedDependencies = {
productModuleService: IProductModuleService
}
class HelloWorldService extends TransactionBaseService {
protected productModuleService: IProductModuleService
constructor({ productModuleService }: InjectedDependencies) {
super(arguments[0])
this.productModuleService = productModuleService
}
// ...
}
export default HelloWorldService
```
Then, use the `TransactionBaseService`'s `atomicPhase_` method that allows you to wrap operations within transactions.
For example:
```ts title="src/services/hello-world.ts" highlights={[["11"]]}
// other imports...
import { ProductDTO, UpdateProductDTO } from "@medusajs/types"
class HelloWorldService extends TransactionBaseService {
// ...
async updateProduct(
productId: string,
data: UpdateProductDTO
): Promise<ProductDTO> {
return await this.atomicPhase_(async (manager) => {
// TODO perform db operation...
})
}
}
```
In the `updateProduct` method, you use the `atomicPhase_` method to wrap the methods implementation.
The `atomicPhase_` method accepts a function as a parameter. All database operations performed in the function are wrapped in a transaction. So, if an error occurs in the function, the operations database changes are rolled back.
The data returned by the function parameter is then returned by the `atomicPhase_` method.