| title | Create Reusable Tasks | ||
|---|---|---|---|
| description | Build task functions that work across multiple flows | ||
| sidebar |
|
import { Aside, Steps, CardGrid, LinkCard } from "@astrojs/starlight/components";
To create task functions that can be used across multiple flows without tight coupling to specific flow structures.
-
Define task parameters
Identify exactly what data the task needs to function. Accept specific parameters, not entire input objects:
// ✅ Accept specific parameters async function fetchUserProfile(userId: string) { const response = await fetch(`https://api.example.com/users/${userId}`); return response.json(); } // ❌ Don't accept entire input object async function fetchUserProfile(input: { user: { id: string }) { const response = await fetch(`https://api.example.com/users/${input.user.id}`); return response.json(); }
-
Return JSON-serializable data
Return primitives, plain objects, or arrays. Convert dates to ISO strings:
async function fetchUserProfile(userId: string) { const response = await fetch(`https://api.example.com/users/${userId}`); const user = await response.json(); return { id: user.id, name: user.name, email: user.email, createdAt: new Date(user.created_at).toISOString() // Convert to ISO string }; }
-
Use step handlers as adapters
Let the flow's step handler extract needed data from the flow context:
// Your task function async function fetchUserProfile(userId: string) { const response = await fetch(`https://api.example.com/users/${userId}`); return response.json(); } // Flow uses handler to adapt context to task parameters new Flow<{ userId: string }>({ slug: 'userFlow' }) .step({ slug: 'profile' }, async (input) => await fetchUserProfile(input.run.userId) )
-
Test in isolation
Verify the task works independently of any flow:
// tasks/fetchUserProfile.test.ts import { assertEquals } from "jsr:@std/assert"; import { fetchUserProfile } from "./fetchUserProfile.ts"; Deno.test("fetches user profile", async () => { const result = await fetchUserProfile("user_123", "test-key"); assertEquals(result.id, "user_123"); assertEquals(result.name, "Alice Johnson"); assertEquals(result.email, "alice@example.com"); assertEquals(result.createdAt, "2024-01-15T10:30:00.000Z"); });