|
1
|
import { parseEventPayload } from "../../../utils" |
|
2
|
|
|
3
|
export type SubscriberSnippetGeneratorOptions = { |
|
4
|
event: string |
|
5
|
payload: Record<string, unknown> | string |
|
6
|
} |
|
7
|
|
|
8
|
export const subscriberSnippetGenerator = ({ |
|
9
|
event, |
|
10
|
payload: initialPayload, |
|
11
|
}: SubscriberSnippetGeneratorOptions) => { |
|
12
|
const payload = |
|
13
|
typeof initialPayload === "string" |
|
14
|
? parseEventPayload(initialPayload).payload_for_snippet |
|
15
|
: initialPayload |
|
16
|
// format subscriber name |
|
17
|
const subscriberName = |
|
18
|
event |
|
19
|
.split(".") |
|
20
|
.map((word) => |
|
21
|
word.replace(/-./g, (match) => match.charAt(1).toUpperCase()) |
|
22
|
) |
|
23
|
.map((word, index) => { |
|
24
|
if (index === 0) { |
|
25
|
return word.charAt(0).toLowerCase() + word.slice(1) |
|
26
|
} |
|
27
|
|
|
28
|
return word.charAt(0).toUpperCase() + word.slice(1) |
|
29
|
}) |
|
30
|
.join("") + "Handler" |
|
31
|
// format payload |
|
32
|
const payloadType: Record<string, unknown> = {} |
|
33
|
Object.keys(payload).forEach((key) => { |
|
34
|
const value = payload[key] |
|
35
|
if (Array.isArray(value)) { |
|
36
|
payloadType[key] = `${typeof value[0]}[]` |
|
37
|
} else { |
|
38
|
payloadType[key] = typeof value |
|
39
|
} |
|
40
|
}) |
|
41
|
|
|
42
|
const payloadString = JSON.stringify(payloadType, null, 2).replaceAll( |
|
43
|
/"/g, |
|
44
|
"" |
|
45
|
) |
|
46
|
|
|
47
|
// return the snippet |
|
48
|
return subscriberSnippet |
|
49
|
.replace("{{subscriberName}}", subscriberName) |
|
50
|
.replace("{{event}}", event) |
|
51
|
.replace("{{payload}}", payloadString) |
|
52
|
} |
|
53
|
|
|
54
|
const subscriberSnippet = `import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework" |
|
55
|
|
|
56
|
export default async function {{subscriberName}}({ |
|
57
|
event: { data }, |
|
58
|
container, |
|
59
|
}: SubscriberArgs<{{payload}}>) { |
|
60
|
// TODO handle event |
|
61
|
} |
|
62
|
|
|
63
|
export const config: SubscriberConfig = { |
|
64
|
event: "{{event}}", |
|
65
|
}` |