|
1
|
export const metadata = { |
|
2
|
title: `${pageNumber} Service Constraints`, |
|
3
|
} |
|
4
|
|
|
5
|
# {metadata.title} |
|
6
|
|
|
7
|
This chapter lists constraints to keep in mind when creating a service. |
|
8
|
|
|
9
|
## Use Async Methods |
|
10
|
|
|
11
|
Medusa wraps service method executions to inject useful context or transactions. However, since Medusa can't detect whether the method is asynchronous, it always executes methods in the wrapper with the `await` keyword. |
|
12
|
|
|
13
|
For example, if you have a synchronous `getMessage` method, and you use it in other resources like workflows, Medusa executes it as an async method: |
|
14
|
|
|
15
|
```ts |
|
16
|
await blogModuleService.getMessage() |
|
17
|
``` |
|
18
|
|
|
19
|
So, make sure your service's methods are always async to avoid unexpected errors or behavior. |
|
20
|
|
|
21
|
{/* eslint-disable @medusajs/service-methods-must-be-async */} |
|
22
|
|
|
23
|
```ts highlights={[["8", "", "Method must be async."], ["13", "async", "Correct way of defining the method."]]} |
|
24
|
import { MedusaService } from "@medusajs/framework/utils" |
|
25
|
import Post from "./models/post" |
|
26
|
|
|
27
|
class BlogModuleService extends MedusaService({ |
|
28
|
Post, |
|
29
|
}){ |
|
30
|
// Don't |
|
31
|
getMessage(): string { |
|
32
|
return "Hello, World!" |
|
33
|
} |
|
34
|
|
|
35
|
// Do |
|
36
|
async getMessage(): Promise<string> { |
|
37
|
return "Hello, World!" |
|
38
|
} |
|
39
|
} |
|
40
|
|
|
41
|
export default BlogModuleService |
|
42
|
``` |