Skip to content

Commit 72e323e

Browse files
committed
Invoices example
1 parent 15720df commit 72e323e

File tree

4 files changed

+221
-32
lines changed

4 files changed

+221
-32
lines changed

src/content/docs/workflows/examples/automate-lifecycle-emails.mdx

Lines changed: 0 additions & 15 deletions
This file was deleted.

src/content/docs/workflows/examples/index.mdx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,6 @@ sidebar:
1212

1313
import { GlossaryTooltip, ListExamples } from "~/components"
1414

15-
Explore the following <GlossaryTooltip term="code example">examples</GlossaryTooltip> for D1.
15+
Explore the following <GlossaryTooltip term="code example">examples</GlossaryTooltip> for Workflows.
1616

17-
<ListExamples directory="d1/examples/" />
17+
<ListExamples directory="workflows/examples/" />

src/content/docs/workflows/examples/post-process-r2.mdx

Lines changed: 0 additions & 15 deletions
This file was deleted.
Lines changed: 219 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,219 @@
1+
---
2+
type: example
3+
summary: Send invoice when shopping cart is checked out and paid for
4+
tags:
5+
- Workflows
6+
- D1
7+
- Email Routing
8+
pcx_content_type: configuration
9+
title: Pay cart and send invoice
10+
sidebar:
11+
order: 3
12+
description: Send invoice when shopping cart is checked out and paid for
13+
14+
---
15+
16+
import { TabItem, Tabs } from "~/components"
17+
18+
In this example we implement a Workflow for that is triggered
19+
20+
Once a workflow instance is triggered, it starts polling a [D1](/d1) database for the cart ID until it's been checked out. Once the shopping cart is checked out, we proceed to process the payment with an external provider doing a fetch POST. Finally, assuming everything goes well, we try to send an email using [Email Workers](/email-routing/email-workers/) with the invoice to the customer.
21+
22+
As you can see, Workflows handles all the different service responses and failures; it will retry D1 until the cart is checked out, retry the payment processor if it fails for some reason, and retry sending the email with the invoice if it can't. The developer doesn't have to care about any of that logic, and the workflow can run for hours, handling all the possible conditions until it is completed.
23+
24+
This is obviously a simplified example of processing a shopping cart. We'd assume more steps and additional logic in a real-life scenario, but hopefully, it gives you a good idea of what you can do with Workflows.
25+
26+
```ts
27+
import {
28+
WorkflowEntrypoint,
29+
WorkflowStep,
30+
WorkflowEvent,
31+
} from "cloudflare:workers";
32+
import { EmailMessage } from "cloudflare:email";
33+
import { createMimeMessage } from "mimetext";
34+
35+
// We are using Email Routing to send emails out and D1 for our cart database
36+
type Env = {
37+
CART_WORKFLOW: Workflow;
38+
SEND_EMAIL: any;
39+
DB: any;
40+
};
41+
42+
// Workflow parameters: we expect a cartId
43+
type Params = {
44+
cartId: string;
45+
};
46+
47+
// Adjust this to your Cloudflare zone using Email Routing
48+
const merchantEmail = "[email protected]";
49+
50+
// Uses mimetext npm to generate Email
51+
const genEmail = (email: string, amount: number) => {
52+
const msg = createMimeMessage();
53+
msg.setSender({ name: "Pet shop", addr: merchantEmail });
54+
msg.setRecipient(email);
55+
msg.setSubject("You invoice");
56+
msg.addMessage({
57+
contentType: "text/plain",
58+
data: `Your invoice for ${amount} has been paid. Your products will be shipped shortly.`,
59+
});
60+
61+
return new EmailMessage(merchantEmail, email, msg.asRaw());
62+
};
63+
64+
// Workflow logic
65+
export class cartInvoicesWorkflow extends WorkflowEntrypoint<Env, Params> {
66+
async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
67+
await step.sleep("sleep for a while", "10 seconds");
68+
69+
// Retrieve the cart from the D1 database
70+
// if the cart hasn't been checked out yet retry every 2 minutes, 10 times, otherwise give up
71+
const cart = await step.do(
72+
"retrieve cart",
73+
{
74+
retries: {
75+
limit: 10,
76+
delay: 2000 * 60,
77+
backoff: "constant",
78+
},
79+
timeout: "30 seconds",
80+
},
81+
async () => {
82+
const { results } = await this.env.DB.prepare(
83+
`SELECT * FROM cart WHERE id = ?`,
84+
)
85+
.bind(event.payload.cartId)
86+
.all();
87+
// should return { checkedOut: true, amount: 250 , account: { email: "[email protected]" }};
88+
if(results[0].checkedOut === false) {
89+
throw new Error("cart hasn't been checked out yet");
90+
}
91+
return results[0];
92+
},
93+
);
94+
95+
// Proceed to payment, retry 10 times every minute or give up
96+
const payment = await step.do(
97+
"payment",
98+
{
99+
retries: {
100+
limit: 10,
101+
delay: 1000 * 60,
102+
backoff: "constant",
103+
},
104+
timeout: "30 seconds",
105+
},
106+
async () => {
107+
let resp = await fetch("https://payment-processor.example.com/", {
108+
method: "POST",
109+
headers: {
110+
"Content-Type": "application/json; charset=utf-8",
111+
},
112+
body: JSON.stringify({ amount: cart.amount }),
113+
});
114+
115+
if (!resp.ok) {
116+
throw new Error("payment has failed");
117+
}
118+
119+
return { success: true, amount: cart.amount };
120+
},
121+
);
122+
123+
// Send invoice to the customer, retry 10 times every 5 minutes or give up
124+
// Requires that cart.account.email has previously been validated in Email Routing,
125+
// See https://developers.cloudflare.com/email-routing/email-workers/
126+
await step.do(
127+
"send invoice",
128+
{
129+
retries: {
130+
limit: 10,
131+
delay: 5000 * 60,
132+
backoff: "constant",
133+
},
134+
timeout: "30 seconds",
135+
},
136+
async () => {
137+
const message = genEmail(cart.account.email, payment.amount);
138+
try {
139+
await this.env.SEND_EMAIL.send(message);
140+
} catch (e) {
141+
throw new Error("failed to send invoice");
142+
}
143+
},
144+
);
145+
146+
}
147+
}
148+
149+
// Default page for admin
150+
// Remove in production
151+
152+
export default {
153+
async fetch(req: Request, env: Env): Promise<Response> {
154+
let url = new URL(req.url);
155+
156+
let id = new URL(req.url).searchParams.get("instanceId");
157+
158+
// Get the status of an existing instance, if provided
159+
if (id) {
160+
let instance = await env.CART_WORKFLOW.get(id);
161+
return Response.json({
162+
status: await instance.status(),
163+
});
164+
}
165+
166+
if (url.pathname.startsWith("/new")) {
167+
let instance = await env.CART_WORKFLOW.create({
168+
params: {
169+
cartId: "123"
170+
},
171+
});
172+
return Response.json({
173+
id: instance.id,
174+
details: await instance.status(),
175+
});
176+
}
177+
178+
return new Response(
179+
`<html><body><a href="/new">new instance</a> or add ?instanceId=...</body></html>`,
180+
{
181+
headers: {
182+
"content-type": "text/html;charset=UTF-8",
183+
},
184+
},
185+
);
186+
},
187+
};
188+
```
189+
190+
Here's a minimal package.json:
191+
192+
```json
193+
{
194+
"devDependencies": {
195+
"@cloudflare/workers-types": "^4.20241022.0",
196+
"wrangler": "^3.83.0"
197+
},
198+
"dependencies": {
199+
"mimetext": "^3.0.24"
200+
}
201+
}
202+
```
203+
204+
And finally wrangler.toml:
205+
206+
```toml
207+
name = "cart-invoices"
208+
main = "src/index.ts"
209+
compatibility_date = "2024-10-22"
210+
compatibility_flags = ["experimental", "nodejs_compat" ]
211+
212+
[[workflows]]
213+
name = "cart-invoices-workflow"
214+
binding = "CART_WORKFLOW"
215+
class_name = "cartInvoicesWorkflow"
216+
217+
[[send_email]]
218+
name = "SEND_EMAIL"
219+
```

0 commit comments

Comments
 (0)