execute<T> method
Future<FunctionResponse<T> >
execute<T>(
- String functionName, {
- Map<
String, dynamic> ? payload, - FunctionMethod? method,
Execute a cloud function by name
functionName - Name of the cloud function to execute
payload - Optional data to send to the function
method - HTTP method to use (defaults to GET if no payload, POST if payload provided)
Returns a FunctionResponse with the result and execution metadata
Throws ArgumentError if projectId is invalid
Throws DioException if the request fails
Example:
// Simple GET request
final result = await db.functions.execute('getStats');
// POST request with payload
final result = await db.functions.execute(
'processOrder',
payload: {
'orderId': '12345',
'items': [{'id': 1, 'quantity': 2}]
},
method: FunctionMethod.post
);
print(result.result); // Function output
print(result.executionTime); // Execution time in ms
print(result.output); // Console output
Implementation
Future<FunctionResponse<T>> execute<T>(
String functionName, {
Map<String, dynamic>? payload,
FunctionMethod? method,
}) async {
// Validate projectId again in case it was modified
if (projectId.trim().isEmpty) {
throw ArgumentError(
'Invalid projectId. Please ensure projectId is set in CocobaseConfig.',
);
}
final url = '/functions/$projectId/func/$functionName';
// Default to GET if no payload, POST if payload provided
final requestMethod = method ?? (payload != null ? FunctionMethod.post : FunctionMethod.get);
try {
Response response;
if (requestMethod == FunctionMethod.get) {
response = await _dio.get(url);
} else {
// POST request
final body = payload != null ? {'payload': payload} : null;
response = await _dio.post(url, data: body);
}
return FunctionResponse<T>.fromJson(response.data as Map<String, dynamic>);
} on DioException catch (e) {
// If the server returned an error response, try to parse it as FunctionResponse
if (e.response?.data != null) {
try {
return FunctionResponse<T>.fromJson(
e.response!.data as Map<String, dynamic>,
);
} catch (_) {
// If parsing fails, rethrow original error
rethrow;
}
}
rethrow;
}
}