Supabase Functions Documentation
This document provides comprehensive documentation for all Supabase Edge Functions in the STO Education Platform backend.Edge Functions Overview
The application uses Supabase Edge Functions (Deno runtime) to handle server-side logic, API integrations, and webhook processing. All functions are deployed to Supabase and handle various aspects of the platform’s backend functionality.Function Categories
1. Email Functions
send-email
Location:supabase/functions/send-email/index.ts
Purpose: Handles email sending through Resend API with template support
Features:
- Template System: Multiple email templates for different use cases
- Resend Integration: Uses Resend API for reliable email delivery
- HTML Templates: Rich HTML email templates with styling
- Error Handling: Comprehensive error handling and logging
- CORS Support: Proper CORS headers for web requests
account-activated: Welcome email for activated accountsaccount-inactive: Account suspension notificationaccount-rejected: Application rejection notificationpayment-success: Payment confirmation emailnew-enrollment: Teacher notification for new student enrollment
RESEND_API_KEY: Resend API key for email sending
2. Payment Functions
payment-webhook
Location:supabase/functions/payment-webhook/index.ts
Purpose: Handles PayMob payment webhook notifications and processes payment completion
Features:
- Webhook Processing: Handles PayMob webhook notifications
- Order Management: Updates order status based on payment results
- Course Assignment: Creates course enrollments for successful payments
- Email Notifications: Sends confirmation emails to users
- Training Course Support: Handles training course enrollments
- Teacher Mark Scheme Support: Processes mark scheme purchases
- Access Period Calculation: Calculates course access periods
- Duplicate Prevention: Prevents duplicate processing of webhooks
sessionorby_class: Single session accessby_week: Weekly accessby_month: Monthly access
- Webhook Validation: Validates webhook data structure
- Order Lookup: Finds order by merchant_order_id
- Status Check: Prevents duplicate processing
- Order Update: Updates order status (completed/failed)
- Course Assignment: Creates course enrollment for successful payments
- Email Notification: Sends confirmation emails
- Access Period: Calculates and sets course access end date
- Training Courses: Creates training enrollments
- Teacher Mark Schemes: Updates purchase status
- Parent Accounts: Handles parent-student relationships
- Access Period Calculation: Smart calculation based on course availability
- Missing Data: Graceful handling of missing webhook data
- Order Not Found: Proper error responses
- Duplicate Processing: Prevents duplicate webhook processing
- Email Failures: Continues processing even if emails fail
3. Video Conferencing Functions
get-hms-token
Location:supabase/functions/get-hms-token/index.ts
Purpose: Generates authentication tokens for 100ms video conferencing
Features:
- Token Generation: Creates secure tokens for video sessions
- Role-based Access: Supports different user roles (teacher/student)
- Room Management: Associates tokens with specific rooms
- Expiration Handling: Sets appropriate token expiration times
- Error Handling: Comprehensive error handling and logging
HMS_MANAGEMENT_TOKEN: 100ms management API token
- Expiration: 24 hours from generation
- Room Association: Tokens are tied to specific rooms
- Role-based Permissions: Different permissions for teachers and students
4. Communication Functions
sendbird-webhook
Location:supabase/functions/sendbird-webhook/index.ts
Purpose: Handles SendBird webhook notifications for chat events
Features:
- Message Notifications: Processes incoming message webhooks
- User Management: Handles user-related webhook events
- Channel Management: Processes channel creation and updates
- Real-time Updates: Triggers real-time database updates
- Message sent notifications
- User join/leave events
- Channel creation/update events
- Custom events
send-message-notification
Location:supabase/functions/send-message-notification/index.ts
Purpose: Sends push notifications for new messages
Features:
- Push Notifications: Sends notifications for new messages
- User Targeting: Targets specific users or groups
- Message Content: Includes message preview in notifications
- Delivery Tracking: Tracks notification delivery status
5. Session Management Functions
create-room
Location:supabase/functions/create-room/index.ts
Purpose: Creates new video conferencing rooms
Features:
- Room Creation: Creates new 100ms rooms
- Template Configuration: Uses predefined room templates
- User Assignment: Assigns users to created rooms
- Room Metadata: Stores room information in database
delete-rooms
Location:supabase/functions/delete-rooms/index.ts
Purpose: Deletes expired or unused video rooms
Features:
- Bulk Deletion: Deletes multiple rooms at once
- Expiration Check: Identifies expired rooms
- Cleanup: Removes associated database records
- Scheduled Execution: Can be run on a schedule
cleanup-sessions
Location:supabase/functions/cleanup-sessions/index.ts
Purpose: Cleans up expired sessions and related data
Features:
- Session Cleanup: Removes expired session data
- Database Maintenance: Cleans up orphaned records
- Performance Optimization: Improves database performance
- Automated Execution: Runs automatically on schedule
6. Quiz and Assessment Functions
notify-quiz-students
Location:supabase/functions/notify-quiz-students/index.ts
Purpose: Sends notifications to students about new quizzes
Features:
- Student Notifications: Notifies students about new quizzes
- Email Integration: Sends email notifications
- Push Notifications: Sends push notifications
- Batch Processing: Handles multiple students efficiently
7. Utility Functions
url-preview
Location:supabase/functions/url-preview/index.ts
Purpose: Generates URL previews for shared links
Features:
- Link Preview: Generates previews for shared URLs
- Metadata Extraction: Extracts title, description, and images
- Caching: Caches preview data for performance
- Error Handling: Handles invalid or inaccessible URLs
download-app-asset
Location:supabase/functions/download-app-asset/index.ts
Purpose: Serves mobile app assets and updates
Features:
- Asset Serving: Serves mobile app files
- Version Management: Handles different app versions
- Update Distribution: Distributes app updates
- Security: Ensures secure asset delivery
get-app-releases
Location:supabase/functions/get-app-releases/index.ts
Purpose: Provides information about available app releases
Features:
- Release Information: Returns available app releases
- Version Details: Provides version-specific information
- Update Notifications: Notifies about new releases
- Platform Support: Handles multiple platforms
8. Session Management Functions
update_session
Location:supabase/functions/update_session/index.ts
Purpose: Updates session information and status
Features:
- Session Updates: Updates session metadata
- Status Management: Manages session status changes
- User Tracking: Tracks user session participation
- Real-time Updates: Provides real-time session updates
hms-webhook
Location:supabase/functions/hms-webhook/index.ts
Purpose: Handles 100ms webhook notifications
Features:
- Event Processing: Processes 100ms webhook events
- Session Tracking: Tracks session lifecycle events
- User Management: Handles user join/leave events
- Database Updates: Updates session records in database
9. Payment Processing Functions
payment-callback
Location:supabase/functions/payment-callback/index.ts
Purpose: Handles payment callback notifications
Features:
- Callback Processing: Processes payment callbacks
- Status Updates: Updates payment status
- Error Handling: Handles payment errors
- Notification Sending: Sends payment notifications
payment-webhook-multiple
Location:supabase/functions/payment-webhook-multiple/index.ts
Purpose: Handles multiple payment webhook notifications
Features:
- Batch Processing: Processes multiple payment notifications
- Parallel Processing: Handles multiple payments simultaneously
- Error Recovery: Recovers from individual payment failures
- Performance Optimization: Optimized for high-volume processing
10. Content Generation Functions
generate-blog-post
Location:supabase/functions/generate-blog-post/index.ts
Purpose: Generates blog post content using AI
Features:
- AI Content Generation: Generates blog post content
- SEO Optimization: Optimizes content for search engines
- Content Validation: Validates generated content
- Database Integration: Saves generated content to database
Function Configuration
Environment Variables
Each function requires specific environment variables:Common Variables
SUPABASE_URL: Supabase project URLSUPABASE_SERVICE_ROLE_KEY: Service role key for admin operations
Function-specific Variables
RESEND_API_KEY: For email functionsHMS_MANAGEMENT_TOKEN: For video conferencing functionsSENDBIRD_API_TOKEN: For chat functionsPAYMOB_SECRET_KEY: For payment functions
CORS Configuration
All functions include CORS headers for web access:Error Handling
Functions implement comprehensive error handling:Function Deployment
Deployment Process
Functions are deployed using Supabase CLI:Local Development
Functions can be run locally for development:Function Monitoring
Logging
All functions include comprehensive logging:Error Tracking
Functions log errors for monitoring:Function Security
Authentication
Functions validate requests:Input Validation
Functions validate input data:Function Performance
Optimization Strategies
- Efficient Database Queries: Optimized database operations
- Caching: Caching for frequently accessed data
- Batch Processing: Processing multiple items efficiently
- Error Recovery: Graceful error handling and recovery
Monitoring
- Response Times: Monitor function execution times
- Error Rates: Track function error rates
- Resource Usage: Monitor memory and CPU usage
- Success Rates: Track function success rates
Future Function Enhancements
Planned Features
- Advanced Caching: Redis integration for better caching
- Message Queues: Background job processing
- Advanced Analytics: Enhanced analytics and reporting
- AI Integration: More AI-powered features
Performance Improvements
- Function Optimization: Better performance optimization
- Database Optimization: Improved database queries
- Caching Strategies: Advanced caching mechanisms
- Load Balancing: Better load distribution
Function Testing
Testing Strategy
- Unit Tests: Test individual function logic
- Integration Tests: Test function interactions
- End-to-End Tests: Test complete workflows
- Load Tests: Test function performance under load
Testing Tools
- Deno Test: Built-in testing framework
- Mock Data: Test with mock data
- Error Simulation: Test error scenarios
- Performance Testing: Test function performance