|
1
|
import { createRule } from "../../create-rule" |
|
2
|
import { |
|
3
|
collectMiddlewareRoutes, |
|
4
|
findAllowFieldsCall, |
|
5
|
findRequestFieldsMutation, |
|
6
|
getDefineMiddlewaresArg, |
|
7
|
RequestFieldsProperty, |
|
8
|
} from "../../util/middlewares" |
|
9
|
|
|
10
|
type MessageIds = "methodScoped" |
|
11
|
|
|
12
|
const FIELDS_PROPERTIES: RequestFieldsProperty[] = ["allowed", "disallowed"] |
|
13
|
|
|
14
|
export const rule = createRule<[], MessageIds>({ |
|
15
|
name: "allow-fields-must-be-global-middleware", |
|
16
|
meta: { |
|
17
|
type: "problem", |
|
18
|
docs: { |
|
19
|
description: |
|
20
|
"Allowed and disallowed fields must be set by a global middleware. Medusa runs a method-scoped middleware after it validates the query parameters, so `allowFields`, `req.allowed`, and `req.disallowed` have no effect there.", |
|
21
|
}, |
|
22
|
messages: { |
|
23
|
methodScoped: |
|
24
|
"`{{source}}` has no effect in a middleware scoped with `{{key}}`, since Medusa validates the query parameters before it runs. Remove the `{{key}}` property so the middleware applies to every request that matches the route.", |
|
25
|
}, |
|
26
|
schema: [], |
|
27
|
}, |
|
28
|
defaultOptions: [], |
|
29
|
create(context) { |
|
30
|
return { |
|
31
|
CallExpression(node) { |
|
32
|
const arg = getDefineMiddlewaresArg(node) |
|
33
|
if (!arg) { |
|
34
|
return |
|
35
|
} |
|
36
|
|
|
37
|
for (const route of collectMiddlewareRoutes(arg)) { |
|
38
|
const methodProperty = route.methodProperty |
|
39
|
if (!methodProperty) { |
|
40
|
continue |
|
41
|
} |
|
42
|
|
|
43
|
const key = |
|
44
|
methodProperty.key.type === "Identifier" |
|
45
|
? methodProperty.key.name |
|
46
|
: "method" |
|
47
|
|
|
48
|
for (const middleware of route.middlewares) { |
|
49
|
const allowFieldsCall = findAllowFieldsCall(middleware) |
|
50
|
if (allowFieldsCall) { |
|
51
|
context.report({ |
|
52
|
node: allowFieldsCall, |
|
53
|
messageId: "methodScoped", |
|
54
|
data: { source: "allowFields", key }, |
|
55
|
}) |
|
56
|
continue |
|
57
|
} |
|
58
|
|
|
59
|
for (const property of FIELDS_PROPERTIES) { |
|
60
|
const mutation = findRequestFieldsMutation(middleware, property) |
|
61
|
if (mutation) { |
|
62
|
context.report({ |
|
63
|
node: mutation, |
|
64
|
messageId: "methodScoped", |
|
65
|
data: { source: `req.${property}`, key }, |
|
66
|
}) |
|
67
|
} |
|
68
|
} |
|
69
|
} |
|
70
|
} |
|
71
|
}, |
|
72
|
} |
|
73
|
}, |
|
74
|
}) |
|
75
|
|
|
76
|
export default rule |