# Buzzy Functions

Buzzy Functions are AWS Lambda functions that extend your Buzzy applications with custom code for external integrations, AI processing, and complex business logic. They run on Node.js 22 with ESM support and provide a secure, scalable way to handle operations that go beyond standard Buzzy capabilities.

## What are Buzzy Functions?

Buzzy Functions are serverless functions that:

* Run on AWS Lambda with Node.js 22 runtime
* Execute custom JavaScript code for external integrations
* Provide secure authentication and environment variable management
* Include built-in testing and debugging capabilities
* Can be generated using AI from natural language prompts

## Authentication Types

Functions support three authentication modes:

### Buzzy-Only (Default)

* Most secure option using AWS IAM authentication
* Only the Buzzy server can invoke the function
* Recommended for internal integrations and data processing

### Specific Domains

* Allow requests from specified domains
* Useful for webhooks from external services like Stripe
* Configure allowed domains in function settings
* Example: `['https://hooks.stripe.com', 'https://yourdomain.com']`

### Public

* Allow requests from anywhere
* Creates a public API endpoint
* Use with caution and implement proper validation

## Function Structure

All Buzzy Functions must export a `main` function that receives an event object:

```javascript
export const main = async (event) => {
  console.log('Received event:', event);
  
  try {
    // Your custom logic here
    const result = await processData(event.body);
    
    return {
      statusCode: 200,
      body: {
        success: true,
        data: result
      }
    };
  } catch (error) {
    console.error('Function error:', error);
    return {
      statusCode: 500,
      body: {
        success: false,
        error: error.message
      }
    };
  }
};
```

## Environment Variables

Functions can access configuration through environment variables:

```javascript
// Access environment variables
const apiKey = process.env.API_KEY;
const baseUrl = process.env.API_BASE_URL;
const databaseUrl = process.env.DATABASE_URL;
```

Environment variables can reference Constants using the `BUZZYCONSTANTS()` syntax:

```javascript
// In function configuration
API_KEY = BUZZYCONSTANTS('OPENAI_API_KEY')
BASE_URL = BUZZYCONSTANTS('API_BASE_URL')
```

## Available Libraries

Functions include commonly used libraries:

* **axios** - HTTP client for API requests
* **buzzy-api-nodejs** - Official Buzzy API client for data operations

```javascript
import axios from 'axios';
import { 
  login, 
  getMicroAppDataRow, 
  createMicroAppDataRow, 
  updateMicroAppDataRow 
} from 'buzzy-api-nodejs';
```

## Creating Functions

### Manual Creation

1. Navigate to your app's Functions panel
2. Click "Add Function"
3. Configure basic settings:
   * **Name**: Descriptive function name
   * **Description**: What the function does
   * **Authentication Type**: Choose security level
4. Write your function code
5. Configure environment variables
6. Test and deploy

### AI Generation

Generate functions from natural language prompts:

1. Click "Generate with AI"
2. Describe what you want the function to do
3. Optionally provide API documentation URLs
4. Review and customize the generated code
5. Test and deploy

Example prompt:

```
Create a function that takes a user's message, sends it to OpenAI's GPT-4 API, 
and saves the response to a Buzzy datatable called "chat_history"
```

## Testing Functions

The built-in testing interface allows you to:

1. **Configure Test Payload**: Set headers and body for testing
2. **Run Tests**: Execute function with sample data
3. **View Results**: See function output and execution logs
4. **Debug Issues**: Access CloudWatch logs for troubleshooting

Example test payload:

```json
{
  "prompt": "What's the weather like today?",
  "location": "San Francisco",
  "debug": true
}
```

## Deployment

Functions are automatically deployed to AWS Lambda when you:

1. Click "Deploy" in the function editor
2. Wait for deployment to complete
3. Test the deployed function
4. Monitor logs and performance

Deployment creates:

* AWS Lambda function with your code
* Environment variables from your configuration
* Function URL for external access (if needed)
* CloudWatch log group for monitoring

## Integration with Buzzy Apps

### Triggering from Actions

Use the "Run Function" action to call functions from your app:

1. Add a "Run Function" action to a button or form
2. Select the function to execute
3. Configure the scope (screen-level or row-level)
4. Map data from your app to function parameters

### Data Flow

Functions can interact with your Buzzy data using the buzzy-api-nodejs client:

```javascript
export const main = async (event) => {
  // Authenticate with Buzzy
  const auth = await login({
    url: process.env.BUZZY_API_URL,
    email: process.env.BUZZY_API_EMAIL,
    password: process.env.BUZZY_API_PASSWORD
  });
  
  // Read data from Buzzy
  const rows = await getMicroAppDataRows({
    authToken: auth.authToken,
    resourceId: process.env.TARGET_RESOURCE_ID
  });
  
  // Process data with external API
  const processed = await processWithExternalAPI(rows);
  
  // Save results back to Buzzy
  const result = await createMicroAppDataRow({
    authToken: auth.authToken,
    resourceId: process.env.RESULTS_RESOURCE_ID,
    rowData: { result: processed }
  });
  
  return {
    statusCode: 200,
    body: { success: true, rowId: result.body._id }
  };
};
```

## Best Practices

### Security

* Never hardcode API keys or secrets in function code
* Use Constants for all sensitive configuration
* Choose the most restrictive authentication type possible
* Validate all input data

### Performance

* Keep functions lightweight and focused
* Use async/await for better performance
* Implement proper error handling
* Monitor execution time and memory usage

### Debugging

* Use console.log for debugging information
* Include debug flags in your test payloads
* Monitor CloudWatch logs for production issues
* Test thoroughly before deploying

### Code Organization

* Use descriptive function and variable names
* Include comments for complex logic
* Follow consistent error handling patterns
* Structure code for readability and maintenance

## Common Patterns

### API Integration

```javascript
export const main = async (event) => {
  const response = await axios.post(process.env.API_ENDPOINT, {
    data: event.body
  }, {
    headers: {
      'Authorization': `Bearer ${process.env.API_KEY}`,
      'Content-Type': 'application/json'
    }
  });
  
  return {
    statusCode: 200,
    body: response.data
  };
};
```

### Data Transformation

```javascript
export const main = async (event) => {
  const inputData = event.body.data;
  
  const transformed = inputData.map(item => ({
    id: item._id,
    name: item.title,
    value: parseFloat(item.amount),
    timestamp: new Date(item.createdAt).toISOString()
  }));
  
  return {
    statusCode: 200,
    body: { transformed }
  };
};
```

### Webhook Handler

```javascript
export const main = async (event) => {
  // Verify webhook signature
  const signature = event.headers['stripe-signature'];
  const isValid = verifyStripeSignature(event.body, signature);
  
  if (!isValid) {
    return { statusCode: 401, body: { error: 'Invalid signature' } };
  }
  
  // Process webhook
  const webhookData = JSON.parse(event.body);
  await processStripeWebhook(webhookData);
  
  return { statusCode: 200, body: { received: true } };
};
```

## Troubleshooting

### Common Issues

**Function won't deploy**

* Check for syntax errors in your code
* Verify environment variables are properly configured
* Ensure AWS credentials are configured correctly

**Function times out**

* Optimize code for better performance
* Increase timeout settings if needed
* Check for infinite loops or blocking operations

**Environment variables not working**

* Verify Constants are created and named correctly
* Check BUZZYCONSTANTS() syntax
* Ensure secrets are properly encrypted

**External API calls failing**

* Verify API keys and endpoints
* Check network connectivity
* Review API documentation for correct request format

### Getting Help

* Use the built-in testing interface to debug issues
* Check CloudWatch logs for detailed error information
* Review function configuration and environment variables
* Test with simplified payloads to isolate problems
