// steps/api/handle-analysis-results.step.ts
import { type Handlers, type StepConfig } from 'motia'
import { z } from 'zod'
const resultsSchema = z.object({
analysisId: z.string(),
userId: z.string(),
results: z.record(z.any()),
processingTime: z.number(),
completedAt: z.number(),
})
export const config = {
name: 'Handle Analysis Results',
description: 'TypeScript handler for Python analysis results',
flows: ['multi-language-app'],
triggers: [
{
type: 'queue',
topic: 'ts.analysis.complete',
input: resultsSchema,
},
],
enqueues: ['notifications.send'],
} as const satisfies StepConfig
export const handler: Handlers<typeof config> = async (
input,
{ logger, state, enqueue }
) => {
const { analysisId, userId, results, processingTime, completedAt } = input
logger.info('Analysis results received', {
analysisId,
processingTime,
})
// Update analysis state with results
await state.update('analyses', analysisId, [
{ type: 'set', path: 'status', value: 'completed' },
{ type: 'set', path: 'results', value: results },
{ type: 'set', path: 'processingTime', value: processingTime },
{ type: 'set', path: 'completedAt', value: completedAt },
])
// Format results for display
const summary = formatResults(results)
// Send notification to user
await enqueue({
topic: 'notifications.send',
data: {
userId,
type: 'analysis_complete',
message: `Your text analysis is complete: ${summary}`,
analysisId,
},
})
logger.info('Analysis results processed', { analysisId, userId })
}
function formatResults(results: Record<string, any>): string {
const parts: string[] = []
if (results.sentiment) {
parts.push(`Sentiment: ${results.sentiment.label}`)
}
if (results.entities) {
const entityCount = Object.values(results.entities)
.reduce((sum: number, arr: any) => sum + arr.length, 0)
parts.push(`${entityCount} entities found`)
}
if (results.summary) {
parts.push(`${results.summary.wordCount} words`)
}
return parts.join(', ')
}