|
1
|
--- |
|
2
|
sidebar_label: "no-service-mutations-in-api-route" |
|
3
|
--- |
|
4
|
|
|
5
|
export const metadata = { |
|
6
|
title: `no-service-mutations-in-api-route - ESLint plugin rules`, |
|
7
|
} |
|
8
|
|
|
9
|
# {metadata.title} |
|
10
|
|
|
11
|
This rule disallows calling service mutation methods directly from an API route handler. |
|
12
|
|
|
13
|
## Severity |
|
14
|
|
|
15
|
`warn`. This rule is enabled in the [recommended](../../page.mdx#recommended) preset. |
|
16
|
|
|
17
|
## What it Targets |
|
18
|
|
|
19
|
This rule targets `route.ts` and `route.js` files in your project's `src/api` directory. It reports calls to mutation methods, such as `create`, `update`, or `delete` methods, on a service resolved from the container. |
|
20
|
|
|
21
|
The following code is reported by the rule: |
|
22
|
|
|
23
|
```ts title="src/api/admin/products/route.ts" |
|
24
|
export const POST = async (req, res) => { |
|
25
|
const productModule = req.scope.resolve(Modules.PRODUCT) |
|
26
|
await productModule.createProducts(req.body) |
|
27
|
res.status(200).json({}) |
|
28
|
} |
|
29
|
``` |
|
30
|
|
|
31
|
Instead, move the mutation into a workflow and run it: |
|
32
|
|
|
33
|
```ts title="src/api/admin/products/route.ts" |
|
34
|
export const POST = async (req, res) => { |
|
35
|
await createProductWorkflow(req.scope).run({ |
|
36
|
input: req.body, |
|
37
|
}) |
|
38
|
res.status(200).json({}) |
|
39
|
} |
|
40
|
``` |
|
41
|
|
|
42
|
## Why it's Important |
|
43
|
|
|
44
|
Workflows provide rollback, error handling, and a single place to maintain business logic. Calling service mutations directly in a route bypasses these benefits and makes the logic harder to reuse. |
|
45
|
|
|
46
|
Learn more in the [Workflows documentation](!docs!/learn/fundamentals/workflows). |
|
47
|
|
|
48
|
## Fixable |
|
49
|
|
|
50
|
This rule isn't auto-fixable. |
|
51
|
|
|
52
|
## Turn it Off |
|
53
|
|
|
54
|
To turn off this rule, set it to `off` in your ESLint configuration: |
|
55
|
|
|
56
|
```ts title="eslint.config.ts" |
|
57
|
import { defineConfig } from "eslint/config" |
|
58
|
import medusa from "@medusajs/eslint-plugin" |
|
59
|
|
|
60
|
export default defineConfig([ |
|
61
|
...medusa.configs.recommended, |
|
62
|
{ |
|
63
|
rules: { |
|
64
|
"@medusajs/no-service-mutations-in-api-route": "off", |
|
65
|
}, |
|
66
|
}, |
|
67
|
]) |
|
68
|
``` |
|
69
|
|
|
70
|
Or disable it for a single line using an inline comment: |
|
71
|
|
|
72
|
```ts |
|
73
|
// eslint-disable-next-line @medusajs/no-service-mutations-in-api-route |
|
74
|
await productModule.createProducts(req.body) |
|
75
|
``` |