Files
medusa-store/www/apps/book/app/advanced-development/modules/database-operations-in-services/page.mdx
Shahed Nasser 327e446974 docs: general fixes and overall changes (#7258)
* editing halfway

* edited second half

* adjust starter steps

* fix build

* typo fix
2024-05-07 18:00:28 +02:00

70 lines
2.0 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
export const metadata = {
title: `${pageNumber} Database Operations in Service Methods`,
}
# {metadata.title}
In this document, youll learn how to implement database operations, such as creating a record, in the main service.
## Use Data Model Services
The module container has a generated service registered for each data model. You can resolve that service and use it to perform database operations on the data model.
For example:
export const highlights = [
["13", "", "Inject myCustomService, which is the service generated by the container loader for the MyCustom data model."],
["22", "", "Add a new field for the generated service of the MyCustom data model."],
["29", "", "Set the class field to the injected dependency."],
["35", "create", "Use the `create` method of the generated service."]
]
```ts title="src/modules/hello/service.ts" highlights={highlights}
// other imports...
import { ModulesSdkTypes } from "@medusajs/types"
import { MyCustom } from "./models/my-custom"
// ...
// recommended to define type in another file
type CreateMyCustomDTO = {
name: string
}
type InjectedDependencies = {
myCustomService: ModulesSdkTypes.InternalModuleService<any>
}
class HelloModuleService extends ModulesSdkUtils
.abstractModuleServiceFactory<
// ...
>(
// ...
) {
protected myCustomService_: ModulesSdkTypes.InternalModuleService<MyCustom>
constructor(
{ myCustomService }: InjectedDependencies
) {
// @ts-ignore
super(...arguments)
this.myCustomService_ = myCustomService
}
async create(
data: CreateMyCustomDTO
): Promise<MyCustomDTO> {
const myCustom = await this.myCustomService_.create(
data,
context
)
return myCustom
}
}
```
In the above example, you resolve `myCustomService` in the main service's constructor. The `myCustomService` is the generated service for the `myCustom` data model.
Then, in the `create` method of the main service, you use `myCustomService`'s `create` method to create the record.