-
Notifications
You must be signed in to change notification settings - Fork 0
/
choreography.ts
86 lines (75 loc) · 1.87 KB
/
choreography.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { z } from "zod";
import { event, subscription } from "@eventual/core";
export const OrderCreated = event(
"OrderCreated",
z.object({
orderId: z.string(),
})
);
export const PaymentProcessed = event(
"PaymentProcessed",
z.object({
orderId: z.string(),
paymentId: z.string(),
})
);
export const OrderShipped = event(
"OrderShipped",
z.object({
orderId: z.string(),
shipmentId: z.string(),
})
);
export const processOrderPayment = subscription(
"processOrderPayment",
{
events: [OrderCreated],
},
async (event) => {
// process the payment using an API (e.g. stripe)
const paymentId = await chargeCard(event.orderId);
// emit an event that the payment was processed
await PaymentProcessed.emit({
orderId: event.orderId,
paymentId,
});
}
);
async function chargeCard(orderId: string) {
// charge, e.g. call stripe
console.log("processing payment for order", orderId);
return "payment-id";
}
export const shipOrderAfterPayment = subscription(
"shipOrderAfterPayment",
{
events: [PaymentProcessed],
},
async (event) => {
// call the shipOrder API
const shipmentId = await shipOrder(event.orderId);
// publish an event recording that the order has been shipped
await OrderShipped.emit({
orderId: event.orderId,
shipmentId,
});
}
);
async function shipOrder(orderId: string) {
// integrate with the shipping API (etc.)
console.log("shipping order", orderId);
return "shipment-id";
}
export const updateOrderStatusSubscription = subscription(
"updateOrderStatus",
{
events: [OrderShipped],
},
async (event) => {
await updateOrder(event.orderId, { status: "Shipped" });
}
);
async function updateOrder(orderId: string, input: { status: string }) {
// update the order database (e.g. DynamoDB)
console.log("updating order", orderId, input);
}