Practical examples demonstrating common script patterns and use cases
Scripts enable you to build serverless functions that execute custom logic in response to events, schedules, or API calls. These examples demonstrate common patterns for building production-ready scripts.
This example demonstrates event-driven execution with entity extraction. The script subscribes to Telegram messages and voice transcripts containing ticker symbols, then logs each mention to memory.
export async function handler(event) { const { data, transformations } = event; let result = data; // Apply each transformation in sequence for (const transform of transformations) { switch (transform.type) { case 'filter': result = result.filter(transform.predicate); break; case 'map': result = result.map(transform.mapper); break; case 'reduce': result = result.reduce(transform.reducer, transform.initial); break; } } return { transformed: result };}
The script processes the input data through each transformation step and returns the final result. This pattern enables flexible data processing without modifying the script code.
export async function handler(event) { const { type, payload } = event; // Route to appropriate handler based on event type switch (type) { case 'payment.completed': await handlePayment(payload); break; case 'user.created': await sendWelcomeEmail(payload); break; default: console.log('Unhandled event:', type); } return { processed: true };}async function handlePayment(payload) { // Process payment confirmation console.log('Payment processed:', payload.amount);}async function sendWelcomeEmail(payload) { // Send welcome email to new user console.log('Welcome email sent to:', payload.email);}
export async function handler(event) { const now = new Date(); // Fetch latest data from your source const data = await fetchLatestData(); // Process and summarize the data const summary = { timestamp: now.toISOString(), recordsProcessed: data.length, summary: calculateSummary(data) }; // Send notification with results await notifyWebhook(summary); return summary;}
The script executes on schedule (e.g., every 5 minutes) and returns a summary of the processed data. Configure the schedule when creating the script using cron syntax.
Validate input parameters at the start of your handler function:
export async function handler(event) { if (!event.symbols || !Array.isArray(event.symbols)) { return { error: 'symbols must be an array' }; } if (typeof event.threshold !== 'number') { return { error: 'threshold must be a number' }; } // Process validated input}