|
| 1 | +--- |
| 2 | +type: example |
| 3 | +summary: Backup D1 using export API |
| 4 | +tags: |
| 5 | + - Workflows |
| 6 | + - D1 |
| 7 | +pcx_content_type: configuration |
| 8 | +title: Pay cart and send invoice |
| 9 | +sidebar: |
| 10 | + order: 3 |
| 11 | +description: Send invoice when shopping cart is checked out and paid for |
| 12 | + |
| 13 | +--- |
| 14 | + |
| 15 | +import { TabItem, Tabs } from "~/components" |
| 16 | + |
| 17 | +In this example, we implement a Workflow for an e-commerce website that is triggered every time a shopping cart is created. |
| 18 | + |
| 19 | +Once a Workflow instance is triggered, it starts polling a [D1](/d1) database for the cart ID until it has 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. |
| 20 | + |
| 21 | +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. |
| 22 | + |
| 23 | +This is a simplified example of processing a shopping cart. We would assume more steps and additional logic in a real-life scenario, but this example gives you a good idea of what you can do with Workflows. |
| 24 | + |
| 25 | +```ts |
| 26 | +import { |
| 27 | + WorkflowEntrypoint, |
| 28 | + WorkflowStep, |
| 29 | + WorkflowEvent, |
| 30 | +} from "cloudflare:workers"; |
| 31 | + |
| 32 | + |
| 33 | +// We are using Email Routing to send emails out and D1 for our cart database |
| 34 | +type Env = { |
| 35 | + BACKUP_WORKFLOW: Workflow; |
| 36 | + D1_REST_API_TOKEN: string; |
| 37 | + BACKUP_BUCKET: R2Bucket; |
| 38 | +}; |
| 39 | + |
| 40 | +// Workflow parameters: we expect a cartId |
| 41 | +type Params = { |
| 42 | + accountId: string; |
| 43 | + databaseId: string; |
| 44 | +}; |
| 45 | + |
| 46 | +// Workflow logic |
| 47 | +export class backupWorkflow extends WorkflowEntrypoint<Env, Params> { |
| 48 | + async run(event: WorkflowEvent<Params>, step: WorkflowStep) { |
| 49 | + |
| 50 | + |
| 51 | + // Retrieve the cart from the D1 database |
| 52 | + // if the cart hasn't been checked out yet retry every 2 minutes, 10 times, otherwise give up |
| 53 | + const cart = await step.do( |
| 54 | + "retrieve cart", |
| 55 | + { |
| 56 | + retries: { |
| 57 | + limit: 10, |
| 58 | + delay: 2000 * 60, |
| 59 | + backoff: "constant", |
| 60 | + }, |
| 61 | + timeout: "30 seconds", |
| 62 | + }, |
| 63 | + async () => { |
| 64 | + const { results } = await this.env.DB.prepare( |
| 65 | + `SELECT * FROM cart WHERE id = ?`, |
| 66 | + ) |
| 67 | + .bind(event.payload.cartId) |
| 68 | + .all(); |
| 69 | + // should return { checkedOut: true, amount: 250 , account: { email: "[email protected]" }}; |
| 70 | + if(results[0].checkedOut === false) { |
| 71 | + throw new Error("cart hasn't been checked out yet"); |
| 72 | + } |
| 73 | + return results[0]; |
| 74 | + }, |
| 75 | + ); |
| 76 | + |
| 77 | + // Proceed to payment, retry 10 times every minute or give up |
| 78 | + const payment = await step.do( |
| 79 | + "payment", |
| 80 | + { |
| 81 | + retries: { |
| 82 | + limit: 10, |
| 83 | + delay: 1000 * 60, |
| 84 | + backoff: "constant", |
| 85 | + }, |
| 86 | + timeout: "30 seconds", |
| 87 | + }, |
| 88 | + async () => { |
| 89 | + let resp = await fetch("https://payment-processor.example.com/", { |
| 90 | + method: "POST", |
| 91 | + headers: { |
| 92 | + "Content-Type": "application/json; charset=utf-8", |
| 93 | + }, |
| 94 | + body: JSON.stringify({ amount: cart.amount }), |
| 95 | + }); |
| 96 | + |
| 97 | + if (!resp.ok) { |
| 98 | + throw new Error("payment has failed"); |
| 99 | + } |
| 100 | + |
| 101 | + return { success: true, amount: cart.amount }; |
| 102 | + }, |
| 103 | + ); |
| 104 | + |
| 105 | + // Send invoice to the customer, retry 10 times every 5 minutes or give up |
| 106 | + // Requires that cart.account.email has previously been validated in Email Routing, |
| 107 | + // See https://developers.cloudflare.com/email-routing/email-workers/ |
| 108 | + await step.do( |
| 109 | + "send invoice", |
| 110 | + { |
| 111 | + retries: { |
| 112 | + limit: 10, |
| 113 | + delay: 5000 * 60, |
| 114 | + backoff: "constant", |
| 115 | + }, |
| 116 | + timeout: "30 seconds", |
| 117 | + }, |
| 118 | + async () => { |
| 119 | + const message = genEmail(cart.account.email, payment.amount); |
| 120 | + try { |
| 121 | + await this.env.SEND_EMAIL.send(message); |
| 122 | + } catch (e) { |
| 123 | + throw new Error("failed to send invoice"); |
| 124 | + } |
| 125 | + }, |
| 126 | + ); |
| 127 | + |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +export default { |
| 132 | + async fetch(req: Request, env: Env): Promise<Response> { |
| 133 | + return new Response("Not found", { status: 404 }); |
| 134 | + }, |
| 135 | + async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext) { |
| 136 | + const params: Params = { |
| 137 | + accountId: "{account_id}", |
| 138 | + databaseId: "{database_id}, |
| 139 | + }; |
| 140 | + const instance = await env.BACKUP_WORKFLOW.create({ params }); |
| 141 | + console.log(`Started workflow: ${instance.id}`); |
| 142 | + }, |
| 143 | +}; |
| 144 | +``` |
| 145 | + |
| 146 | +Here's a minimal package.json: |
| 147 | + |
| 148 | +```json |
| 149 | +{ |
| 150 | + "devDependencies": { |
| 151 | + "@cloudflare/workers-types": "^4.20241224.0", |
| 152 | + "wrangler": "^3.99.0" |
| 153 | + } |
| 154 | +} |
| 155 | +``` |
| 156 | + |
| 157 | +And finally wrangler.toml: |
| 158 | + |
| 159 | +import { WranglerConfig } from "~/components"; |
| 160 | + |
| 161 | +<WranglerConfig> |
| 162 | + |
| 163 | +```toml |
| 164 | +name = "backup-d1" |
| 165 | +main = "src/index.ts" |
| 166 | +compatibility_date = "2024-12-27" |
| 167 | +compatibility_flags = ["nodejs_compat" ] |
| 168 | + |
| 169 | +[[workflows]] |
| 170 | +name = "backup-workflow" |
| 171 | +binding = "BACKUP_WORKFLOW" |
| 172 | +class_name = "backupWorkflow" |
| 173 | + |
| 174 | +[triggers] |
| 175 | +crons = [ "0 0 * * *" ] |
| 176 | + |
| 177 | +``` |
| 178 | + |
| 179 | +</WranglerConfig> |
0 commit comments