call method

Future<Output> call({
  1. required Input input,
  2. Init? init,
  3. Map<String, String>? headers,
})

Invokes the remote flow.

Implementation

Future<Output> call({
  required Input input,
  Init? init,
  Map<String, String>? headers,
}) async {
  final uri = Uri.parse(_url);
  final requestHeaders = {
    'Content-Type': 'application/json',
    ...?_defaultHeaders,
    ...?headers,
  };
  final requestBody = jsonEncode({'data': input, 'init': ?init});

  http.Response response;
  try {
    response = await _httpClient.post(
      uri,
      headers: requestHeaders,
      body: requestBody,
    );
  } catch (e, s) {
    throw GenkitException(
      'HTTP request failed: ${e.toString()}',
      cause: e,
      stackTrace: s,
    );
  }

  if (response.statusCode != 200) {
    throw _httpError(response.statusCode, response.body);
  }

  dynamic decodedBody;
  try {
    decodedBody = jsonDecode(response.body);
  } on FormatException catch (e, s) {
    throw GenkitException(
      'Failed to decode JSON response: ${e.toString()}',
      cause: e,
      details: response.body,
      stackTrace: s,
    );
  }

  if (decodedBody is Map<String, dynamic>) {
    if (decodedBody.containsKey('error')) {
      final errorData = decodedBody['error'];
      throw _errorPayload(errorData, 'Unknown server error');
    }
    if (decodedBody.containsKey('result')) {
      return _fromResponse(decodedBody['result']);
    }
  }

  // Fallback for non-standard successful responses.
  return _fromResponse(decodedBody);
}