UNPKG

workflow

Version:

Workflow SDK - Build durable, resilient, and observable workflows

101 lines (79 loc) • 2.28 kB
--- title: getStepMetadata description: Access retry attempts and timing information within step functions. type: reference summary: Call getStepMetadata inside a step to access retry counts, timing, and idempotency keys. prerequisites: - /docs/foundations/workflows-and-steps --- Returns metadata available in the current step function. You may want to use this function when you need to: - Track retry attempts in error handling - Access timing information of a step and execution metadata - Generate idempotency keys for external APIs <Callout type="warn"> This function can only be called inside a step function. </Callout> ```typescript lineNumbers import { getStepMetadata } from "workflow"; async function testWorkflow() { "use workflow"; await logStepId(); } async function logStepId() { "use step"; const ctx = getStepMetadata(); // [!code highlight] console.log(ctx.stepId); // Grab the current step ID } ``` ### Example: use `stepId` as an idempotency key ```typescript lineNumbers import { getStepMetadata } from "workflow"; async function chargeUser(userId: string, amount: number) { "use step"; const { stepId } = getStepMetadata(); await stripe.charges.create( { amount, currency: "usd", customer: userId, }, { idempotencyKey: `charge:${stepId}`, // [!code highlight] } ); } ``` <Callout type="info"> Learn more about patterns and caveats in the{" "} <a href="/docs/foundations/idempotency">Idempotency</a> guide. </Callout> ### Example: handle the last attempt differently ```typescript lineNumbers import { getStepMetadata } from "workflow"; async function welcomeUser(userId: string) { "use step"; const { attempt, maxAttempts } = getStepMetadata(); try { return await sendWelcomeEmail(userId); } catch (error) { if (attempt < maxAttempts) throw error; // [!code highlight] console.error(`Giving up on the welcome email for ${userId}`, error); return null; } } ``` ## API signature ### Parameters <TSDoc definition={` import { getStepMetadata } from "workflow"; export default getStepMetadata;`} showSections={["parameters"]} /> ### Returns <TSDoc definition={` import type { StepMetadata } from "workflow"; export default StepMetadata;`} />