docs: general fixes and overall changes (#7258)
* editing halfway * edited second half * adjust starter steps * fix build * typo fix
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
export const metadata = {
|
||||
title: `${pageNumber} Transactions in Services`,
|
||||
}
|
||||
|
||||
# {metadata.title}
|
||||
|
||||
In this chapter, you’ll 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 method’s 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 method’s 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.
|
||||
|
||||
Reference in New Issue
Block a user