Call a REST API through a binding
Call an external REST/JSON endpoint from a workflow using Node’s built-in
fetch, keeping URL construction, headers, timeouts, response parsing, and
status-code classification inside a named
binding. The Workflow Test replaces
the binding with a fixture so retries and fallbacks run against PostgreSQL with
no network calls; a plain Vitest unit test checks the HTTP adapter with a
stubbed fetch.
- Starter project: save
src/workflows/http-binding.workflow.tsandtests/workflows/http-binding.workflow.case.ts, change the test import from'./http-binding.workflow'to'../../src/workflows/http-binding.workflow', then runnpm run checkandnpm run test:workflow -- tests/workflows/http-binding.workflow.case.ts. - Standalone project: save
http-binding.workflow.tsandhttp-binding.workflow.case.tsin the same folder (keep the'./http-binding.workflow'import), then runnpx tsc --noEmitand/path/to/identity-flow-test --run http-binding.workflow.case.ts. See Before you start.
import process from 'node:process';
import { defineBinding, defineWorkflow, isAbortError, NonRetryableError } from '@identity-flow/sdk';import * as v from '@identity-flow/sdk/valibot';
export interface AccountRequest { readonly employeeId: string; readonly role: string; readonly idempotencyKey: string;}
export interface AccountRecord { readonly id: string; readonly status: 'active' | 'pending';}
export interface AccountProvisioning { createAccount(request: AccountRequest, signal: AbortSignal): Promise<AccountRecord>;}
const AccountResponseSchema = v.object({ id: v.pipe(v.string(), v.nonEmpty()), status: v.picklist(['active', 'pending']),});
export interface AccountProvisioningClientOptions { readonly baseUrl?: string; readonly token?: () => string; readonly timeoutMs?: number;}
/** Pure HTTP/JSON adapter: validates responses and separates permanent from transient HTTP errors. */export function createAccountProvisioningClient( options: AccountProvisioningClientOptions = {},): AccountProvisioning { const baseUrl = ( options.baseUrl ?? process.env['ACME_API_BASE_URL'] ?? 'https://accounts.example.com' ).replace(/\/+$/, ''); const readToken = options.token ?? (() => process.env['ACME_API_TOKEN'] ?? ''); const timeoutMs = options.timeoutMs ?? 5_000;
return { async createAccount(request, signal) { const response = await fetch( `${baseUrl}/v1/employees/${encodeURIComponent(request.employeeId)}/accounts`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${readToken()}`, 'idempotency-key': request.idempotencyKey, }, body: JSON.stringify({ role: request.role }), signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]), }, );
// fetch resolves on 4xx and 5xx; classify permanent client errors vs. retryable failures. if (!response.ok) { if (response.status === 429 || response.status >= 500) { throw new Error(`Account API transient failure: HTTP ${response.status}`); } throw new NonRetryableError(`Account API rejected request: HTTP ${response.status}`); }
return v.parse(AccountResponseSchema, await response.json()); }, };}
export const AccountProvisioning = defineBinding('account-provisioning', (): AccountProvisioning => createAccountProvisioningClient(),);
export const provisionAccount = defineWorkflow( { name: 'provision-account', version: '1.0.0', draft: false, schema: v.object({ employeeId: v.pipe(v.string(), v.nonEmpty()), role: v.pipe(v.string(), v.nonEmpty()), }), }, async (flow) => { const provisioning = flow.use(AccountProvisioning);
try { const account = await flow.do( 'create account', { retries: { limit: 3, delay: 50 } }, async ({ step, signal }) => await provisioning.createAccount( { employeeId: flow.params.employeeId, role: flow.params.role, idempotencyKey: step.id }, signal, ), ); return { outcome: 'provisioned' as const, account }; } catch (error: unknown) { if (isAbortError(error)) throw error; return { outcome: 'manual-review' as const, reason: error instanceof Error ? error.message : String(error), }; } },);
export default provisionAccount;Key design points for production HTTP bindings:
- Combine step cancellation and per-request timeouts:
AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)])cancels the outboundfetchwhen either the workflow step cancels or the per-request budget expires (similar tocontext.WithTimeoutin Go). - Check
response.okexplicitly: unlike some HTTP client wrappers,fetchresolves on4xxand5xxresponses. Throw a plainErrorfor transient statuses (429,5xx) soflow.doretries after the configured delay, andNonRetryableErrorfor permanent client rejections (400,404) so the step stops immediately. - Forward
step.idas an idempotency key:step.idstays constant across every retry of the same step, letting the remote REST API deduplicate retried writes safely. - Validate JSON responses with Valibot:
v.parse(AccountResponseSchema, await response.json())guarantees the returned object matches theAccountRecordtype before it enters the workflow’s recorded history. - Keep
if (isAbortError(error)) throw error;in workflow fallbacks: rethrow cancellation errors so workflow shutdown or race cancellation is never swallowed as a business fallback.
signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]),- step cancellation
- per-attempt budget
Coming from Go? See the
TypeScript idioms guide
for AbortSignal, as const, ??, same-name interface/value bindings, and
catch (error: unknown).
import { NonRetryableError } from '@identity-flow/sdk';import { workflowTest } from '@identity-flow/testing';import { expect, vi } from 'vitest';
import { AccountProvisioning, provisionAccount } from './http-binding.workflow';
const test = workflowTest({ workflow: provisionAccount, accounts: { starter: { providerId: 'acme', principals: ['role:it-admin'] } },});
test('retries a transient failure with the same step idempotency key', async ({ flow, accounts, fixture,}) => { const createAccount = vi .fn<AccountProvisioning['createAccount']>() .mockRejectedValueOnce(new Error('Account API transient failure: HTTP 503')) .mockResolvedValueOnce({ id: 'acct-42', status: 'active' }); fixture(AccountProvisioning, { createAccount });
const instance = await flow .actAs(accounts.starter) .start({ employeeId: 'e-2041', role: 'engineer' }); const completed = await flow.waitFor(instance).toBeCompleted();
expect(completed.data).toEqual({ outcome: 'provisioned', account: { id: 'acct-42', status: 'active' }, }); expect(createAccount).toHaveBeenCalledTimes(2); const [firstRequest, firstSignal] = createAccount.mock.calls[0] ?? []; const [secondRequest] = createAccount.mock.calls[1] ?? []; expect(firstRequest?.idempotencyKey).toBeTruthy(); expect(secondRequest?.idempotencyKey).toBe(firstRequest?.idempotencyKey); expect(firstSignal).toBeInstanceOf(AbortSignal);});
test('stops immediately on a permanent client error and falls back to manual review', async ({ flow, accounts, fixture,}) => { const createAccount = vi .fn<AccountProvisioning['createAccount']>() .mockRejectedValue(new NonRetryableError('Account API rejected request: HTTP 404')); fixture(AccountProvisioning, { createAccount });
const instance = await flow .actAs(accounts.starter) .start({ employeeId: 'e-9999', role: 'engineer' }); const completed = await flow.waitFor(instance).toBeCompleted();
expect(completed.data).toEqual({ outcome: 'manual-review', reason: 'Account API rejected request: HTTP 404', }); expect(createAccount).toHaveBeenCalledOnce();});Because createAccountProvisioningClient is exported as a plain factory, test
its fetch behavior (signal forwarding, timeout aborts, Valibot response
validation, and 400/404 vs. 429/5xx status classification) in a fast,
database-free *.test.ts file under plain Vitest:
test.each([400, 404])('treats HTTP %i as NonRetryableError', async (status) => { vi.stubGlobal( 'fetch', vi.fn(() => Promise.resolve(new Response('bad request', { status }))), ); const client = createAccountProvisioningClient({ baseUrl: 'https://accounts.example.test' });
const caught = await client .createAccount( { employeeId: 'e-2041', role: 'engineer', idempotencyKey: 'step-client-err' }, new AbortController().signal, ) .catch((error: unknown) => error);
expect(isNonRetryableError(caught)).toBe(true);});
test.each([429, 500, 503])('leaves HTTP %i retryable', async (status) => { vi.stubGlobal( 'fetch', vi.fn(() => Promise.resolve(new Response('try later', { status }))), ); const client = createAccountProvisioningClient({ baseUrl: 'https://accounts.example.test' });
const caught = await client .createAccount( { employeeId: 'e-2041', role: 'engineer', idempotencyKey: 'step-transient-err' }, new AbortController().signal, ) .catch((error: unknown) => error);
expect(caught).toBeInstanceOf(Error); expect(isNonRetryableError(caught)).toBe(false);});Restore globalThis.fetch after each test (afterEach(() => vi.unstubAllGlobals()))
so stubbed responses never leak into other test files.
Next: Bindings and connectors for binding
design rules, Errors and retries for backoff and
idempotency patterns, and Set up CI to run both *.test.ts unit
tests and *.case.ts Workflow Tests automatically.