TypeScript SDK cookbook
Concrete recipes: middleware, batch, retries, Edge-runtime patterns.
Middleware around an AI call
import { Cohesion } from "@cohesionauth/sdk";
const cohesion = new Cohesion({ apiKey: process.env.COHESION_API_KEY! });
export async function aiWithCohesion(prompt: string, operatorId: string, sessionId: string) {
const start = Date.now();
const aiOut = await callYourAiProvider(prompt);
const elapsedMs = Date.now() - start;
const decision = await captureOperatorDecision(aiOut);
await cohesion.score({
session_id: sessionId,
operator_id: operatorId,
domain: "financial",
interaction: {
ai_recommendation_presented: true,
time_to_decision_ms: elapsedMs,
decision: decision.kind,
modification_extent: decision.editRatio,
ai_available: true,
scenario_type: "standard",
outcome_correct: null,
hover_events: decision.hovers,
scroll_depth: decision.scroll,
alternative_views_checked: decision.altViews,
},
});
return aiOut;
}
Batch backfill
function chunk<T>(arr: T[], size: number): T[][] {
const out: T[][] = [];
for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
return out;
}
for (const interactions of chunk(allInteractions, 100)) {
await cohesion.scoreBatch({ operator_id: "analyst-42", domain: "financial", interactions });
}
Cloudflare Workers
export default {
async fetch(req: Request, env: Env): Promise<Response> {
const cohesion = new Cohesion({ apiKey: env.COHESION_API_KEY });
const resp = await cohesion.score({ /* ... */ });
return Response.json(resp);
},
};
Idempotency keys
await cohesion.score({ /* ... */ }, { idempotencyKey: crypto.randomUUID() });
Handling 429
The SDK retries with exponential backoff automatically. For custom handling:
try {
await cohesion.score({ /* ... */ });
} catch (err) {
if (err instanceof CohesionRateLimitError) {
await sleep(err.retryAfterSeconds * 1000);
// retry
}
}