invoke method

Future<FunctionResponse> invoke(
  1. String functionName, {
  2. Map<String, String>? headers,
  3. Map<String, dynamic>? body,
  4. HttpMethod method = HttpMethod.post,
})

Invokes a function

functionName - the name of the function to invoke

headers: object representing the headers to send with the request

body: the body of the request

Implementation

Future<FunctionResponse> invoke(
  String functionName, {
  Map<String, String>? headers,
  Map<String, dynamic>? body,
  HttpMethod method = HttpMethod.post,
}) async {
  final bodyStr = body == null ? null : await _isolate.encode(body);

  late final Response response;
  final uri = Uri.parse('$_url/$functionName');

  final finalHeaders = <String, String>{
    ..._headers,
    if (headers != null) ...headers
  };

  switch (method) {
    case HttpMethod.post:
      response = await (_httpClient?.post ?? http.post)(
        uri,
        headers: finalHeaders,
        body: bodyStr,
      );
      break;

    case HttpMethod.get:
      response = await (_httpClient?.get ?? http.get)(
        uri,
        headers: finalHeaders,
      );
      break;

    case HttpMethod.put:
      response = await (_httpClient?.put ?? http.put)(
        uri,
        headers: finalHeaders,
        body: bodyStr,
      );
      break;

    case HttpMethod.delete:
      response = await (_httpClient?.delete ?? http.delete)(
        uri,
        headers: finalHeaders,
      );
      break;

    case HttpMethod.patch:
      response = await (_httpClient?.patch ?? http.patch)(
        uri,
        headers: finalHeaders,
        body: bodyStr,
      );
      break;
  }

  final responseType = (response.headers['Content-Type'] ??
          response.headers['content-type'] ??
          'text/plain')
      .split(';')[0]
      .trim();

  final data = switch (responseType) {
    'application/json' => response.bodyBytes.isEmpty
        ? ""
        : await _isolate.decode(utf8.decode(response.bodyBytes)),
    'application/octet-stream' => response.bodyBytes,
    _ => utf8.decode(response.bodyBytes),
  };
  if (200 <= response.statusCode && response.statusCode < 300) {
    return FunctionResponse(data: data, status: response.statusCode);
  } else {
    throw FunctionException(
      status: response.statusCode,
      details: data,
      reasonPhrase: response.reasonPhrase,
    );
  }
}