Files
medusa-store/www/apps/book/app/basics/_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

78 lines
1.9 KiB
Plaintext

export const metadata = {
title: `${pageNumber} Services`,
}
# {metadata.title}
In this chapter, you'll learn what services are and how to create a service.
## What is a Service?
A service is a class that holds methods related to a business logic or commerce functionality. For example, the `ProductService` holds methods to retrieve and manage products.
---
## How to Create a Service
Services are created in a TypeScript or JavaScript file under the `src/services` directory of your Medusa application.
For example, to create a `HelloWorld` service, create the file `src/services/hello-world.ts` with the following content:
```ts title="src/services/hello-world.ts"
class HelloWorld {
// TODO add methods
}
export default HelloWorld
```
<Note title="Tip">
A service's file name must be the kebab-case name of the service without the word `Service`.
</Note>
---
## When to Use
<Note title="Use services when" type="success">
- You're implementing custom commerce functionality to be reused across the Medusa application.
- You're integrating a third-party service, such as an ERP system.
</Note>
---
## Resolve Resources
In a service's constructor, you can resolve other services or resources of your Medusa application using the Medusa container.
For example, you can resolve the `IProductModuleService` to use it in your methods:
```ts title="src/services/hello-world.ts" highlights={[["10"]]}
import { IProductModuleService } from "@medusajs/types"
type InjectedDependencies = {
productModuleService: IProductModuleService
}
class HelloWorldService {
protected productModuleService: IProductModuleService
constructor({ productModuleService }: InjectedDependencies) {
this.productModuleService = productModuleService
}
async getMessage(): Promise<string> {
const [, count] =
await this.productModuleService.listAndCount()
return `You have ${count} products`
}
}
export default HelloWorldService
```