UNPKG

magically-sdk

Version:

Official SDK for Magically - Build mobile apps with AI

59 lines (58 loc) 2.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MagicallyFunctions = void 0; const APIClient_1 = require("./APIClient"); const Logger_1 = require("./Logger"); class MagicallyFunctions { constructor(config, auth) { this.config = config; this.auth = auth; this.apiClient = new APIClient_1.APIClient(config, 'MagicallyFunctions'); this.logger = new Logger_1.Logger(config.debug || false, 'MagicallyFunctions'); this.projectId = config.projectId; } /** * Invoke a Cloudflare Worker function * @param functionName - The name of the function to invoke * @param options - Options for the function invocation */ async invoke(functionName, options = {}) { const startTime = Date.now(); const method = 'POST'; this.logger.info(`Invoking function: ${functionName} via ${method}`); // Build the endpoint path const endpoint = `/api/functions/v1/${this.projectId}/${functionName}`; try { // Get token following MagicallyData pattern const token = this.apiClient.isEdgeEnvironment() ? null : await this.auth.getValidToken(); // Make the request through APIClient for proper auth and logging const response = await this.apiClient.request(endpoint, { method, headers: options.headers, body: options.body, operation: `invoke_function_${functionName}` }, token); const duration = Date.now() - startTime; this.logger.info(`Function ${functionName} completed in ${duration}ms`); return { data: response, status: 200 }; } catch (error) { const duration = Date.now() - startTime; this.logger.error(`Function ${functionName} failed after ${duration}ms:`, error); // Simple error handling - just pass through the error return { error: { message: error.message || 'An unknown error occurred', code: 'FUNCTION_INVOCATION_ERROR' }, status: 500 }; } } } exports.MagicallyFunctions = MagicallyFunctions;