invokeApi method

Future<Response> invokeApi({
  1. required Method method,
  2. required String path,
  3. Map<String, String> queryParameters = const {},
  4. dynamic body,
  5. Map<String, String> headerParameters = const {},
  6. AuthRequest? authRequest,
})

Implementation

Future<Response> invokeApi({
  required Method method,
  required String path,
  Map<String, String> queryParameters = const {},
  // Body is nullable to allow for post requests which have an optional body
  // to not have to generate two separate calls depending on whether the
  // body is present or not.
  dynamic body,
  Map<String, String> headerParameters = const {},
  AuthRequest? authRequest,
}) async {
  if (!method.supportsBody && body != null) {
    throw ArgumentError('Body is not allowed for ${method.name} requests');
  }

  final auth = resolveAuth(authRequest);
  final uri = _resolveUri(
    path: path,
    queryParameters: queryParameters,
    auth: auth,
  );
  final encodedBody = body != null ? jsonEncode(body) : null;
  final headers = _resolveHeaders(
    bodyIsJson: encodedBody != null,
    headerParameters: headerParameters,
    auth: auth,
  );

  try {
    switch (method) {
      case Method.delete:
        return client.delete(uri, headers: headers);
      case Method.get:
        return client.get(uri, headers: headers);
      case Method.patch:
        return client.patch(uri, headers: headers, body: encodedBody);
      case Method.post:
        return client.post(uri, headers: headers, body: encodedBody);
      case Method.put:
        return client.put(uri, headers: headers, body: encodedBody);
    }
  } on SocketException catch (error, trace) {
    throw ApiException.withInner(
      HttpStatus.badRequest,
      'Socket operation failed: $method $path',
      error,
      trace,
    );
  } on TlsException catch (error, trace) {
    throw ApiException.withInner(
      HttpStatus.badRequest,
      'TLS/SSL communication failed: $method $path',
      error,
      trace,
    );
  } on IOException catch (error, trace) {
    throw ApiException.withInner(
      HttpStatus.badRequest,
      'I/O operation failed: $method $path',
      error,
      trace,
    );
  } on ClientException catch (error, trace) {
    throw ApiException.withInner(
      HttpStatus.badRequest,
      'HTTP connection failed: $method $path',
      error,
      trace,
    );
  } on Exception catch (error, trace) {
    throw ApiException.withInner(
      HttpStatus.badRequest,
      'Exception occurred: $method $path',
      error,
      trace,
    );
  }
}