|
1
|
--- |
|
2
|
sidebar_label: "service-methods-must-be-async" |
|
3
|
--- |
|
4
|
|
|
5
|
export const metadata = { |
|
6
|
title: `service-methods-must-be-async - ESLint plugin rules`, |
|
7
|
} |
|
8
|
|
|
9
|
# {metadata.title} |
|
10
|
|
|
11
|
This rule requires that all public methods on a service class are `async` or return a `Promise`. |
|
12
|
|
|
13
|
## Severity |
|
14
|
|
|
15
|
`error`. This rule is enabled in the [recommended](../../page.mdx#recommended) preset. |
|
16
|
|
|
17
|
## What it Targets |
|
18
|
|
|
19
|
This rule targets service files in your project's `src/modules` directory. It only reports public methods on a class that is recognized as a module service, which is a class that either: |
|
20
|
|
|
21
|
- Extends `MedusaService`. |
|
22
|
- Is defined in a module's `service.ts` file (`src/modules/*/service.ts`). |
|
23
|
- Is defined under a module's `services` directory (`src/modules/*/services/**`). |
|
24
|
|
|
25
|
A class isn't considered a service just because its name ends with `Service`. The rule reports a service class's public method when it isn't `async` and doesn't return a `Promise`. |
|
26
|
|
|
27
|
The following code is reported by the rule: |
|
28
|
|
|
29
|
```ts title="src/modules/blog/service.ts" |
|
30
|
import { MedusaService } from "@medusajs/framework/utils" |
|
31
|
|
|
32
|
class BlogModuleService extends MedusaService({}) { |
|
33
|
create() {} |
|
34
|
} |
|
35
|
``` |
|
36
|
|
|
37
|
Instead, make the method `async`: |
|
38
|
|
|
39
|
```ts title="src/modules/blog/service.ts" |
|
40
|
import { MedusaService } from "@medusajs/framework/utils" |
|
41
|
|
|
42
|
class BlogModuleService extends MedusaService({}) { |
|
43
|
async create() {} |
|
44
|
} |
|
45
|
``` |
|
46
|
|
|
47
|
## Why it's Important |
|
48
|
|
|
49
|
Medusa always awaits service method calls. A method that isn't `async` and doesn't return a `Promise` can lead to unexpected behavior when its result is awaited. |
|
50
|
|
|
51
|
Learn more in the [Service Constraints documentation](!docs!/learn/fundamentals/modules/service-constraints). |
|
52
|
|
|
53
|
## Fixable |
|
54
|
|
|
55
|
This rule is auto-fixable. Run the linter with the `--fix` option to apply the fix automatically. |