Skip to main content

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
Email Templates Supported:
  • account-activated: Welcome email for activated accounts
  • account-inactive: Account suspension notification
  • account-rejected: Application rejection notification
  • payment-success: Payment confirmation email
  • new-enrollment: Teacher notification for new student enrollment
Request Interface:
interface EmailRequest {
  type: string;
  email: string;
  subject: string;
  html: string;
}
Template Data Structure:
interface TemplateData {
  firstName: string;
  lastName: string;
  userType: string;
  // Additional fields based on template type
}
Usage Example:
const response = await fetch('/functions/v1/send-email', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${SUPABASE_ANON_KEY}`
  },
  body: JSON.stringify({
    type: 'payment-success',
    email: '[email protected]',
    subject: 'Payment Successful',
    html: '<html>...</html>'
  })
});
Environment Variables:
  • 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
Webhook Data Structure:
interface PaymobWebhookData {
  obj: {
    id: string;
    success: boolean;
    amount_cents: number;
    currency: string;
    payment_method: string;
    order: {
      id: string;
      merchant_order_id: string;
      created_at: string;
    };
  };
}
Payment Periods Supported:
  • session or by_class: Single session access
  • by_week: Weekly access
  • by_month: Monthly access
Processing Flow:
  1. Webhook Validation: Validates webhook data structure
  2. Order Lookup: Finds order by merchant_order_id
  3. Status Check: Prevents duplicate processing
  4. Order Update: Updates order status (completed/failed)
  5. Course Assignment: Creates course enrollment for successful payments
  6. Email Notification: Sends confirmation emails
  7. Access Period: Calculates and sets course access end date
Special Handling:
  • 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
Error Handling:
  • 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
Request Interface:
interface TokenRequest {
  roomId: string;
  userId: string;
  userName: string;
  role: 'teacher' | 'student';
}
Response Interface:
interface TokenResponse {
  success: boolean;
  authToken: string;
  roomId: string;
  userId: string;
  userName: string;
  role: string;
}
Usage Example:
const response = await fetch('/functions/v1/get-hms-token', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${SUPABASE_ANON_KEY}`
  },
  body: JSON.stringify({
    roomId: 'room-123',
    userId: 'user-456',
    userName: 'John Doe',
    role: 'teacher'
  })
});
Environment Variables:
  • HMS_MANAGEMENT_TOKEN: 100ms management API token
Token Configuration:
  • 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
Webhook Types Supported:
  • 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
Request Interface:
interface CreateRoomRequest {
  roomName: string;
  templateId: string;
  userId: string;
  courseId?: string;
}

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 URL
  • SUPABASE_SERVICE_ROLE_KEY: Service role key for admin operations

Function-specific Variables

  • RESEND_API_KEY: For email functions
  • HMS_MANAGEMENT_TOKEN: For video conferencing functions
  • SENDBIRD_API_TOKEN: For chat functions
  • PAYMOB_SECRET_KEY: For payment functions

CORS Configuration

All functions include CORS headers for web access:
const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}

Error Handling

Functions implement comprehensive error handling:
try {
  // Function logic
} catch (error) {
  console.error('Function error:', error);
  return new Response(
    JSON.stringify({ error: error.message }),
    { status: 500, headers: corsHeaders }
  );
}

Function Deployment

Deployment Process

Functions are deployed using Supabase CLI:
# Deploy all functions
supabase functions deploy

# Deploy specific function
supabase functions deploy function-name

# Deploy with environment variables
supabase functions deploy --env-file .env

Local Development

Functions can be run locally for development:
# Start local development server
supabase functions serve

# Serve specific function
supabase functions serve function-name

Function Monitoring

Logging

All functions include comprehensive logging:
console.log('Function started:', { params });
console.log('Processing data:', data);
console.log('Function completed successfully');

Error Tracking

Functions log errors for monitoring:
console.error('Error in function:', error);
console.error('Error details:', error.message);

Function Security

Authentication

Functions validate requests:
// Check authorization header
const authHeader = req.headers.get('authorization');
if (!authHeader) {
  return new Response('Unauthorized', { status: 401 });
}

Input Validation

Functions validate input data:
if (!requiredField) {
  return new Response(
    JSON.stringify({ error: 'Missing required field' }),
    { status: 400 }
  );
}

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