invokeApi method

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

Implementation

Future<Response> invokeApi({
  required Method method,
  required String path,
  Map<String, List<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.
  Object? body,
  BodyContentType bodyContentType = BodyContentType.json,
  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,
  );
  // Only the JSON path runs through jsonEncode; binary/text bodies pass
  // through so the receiving server gets the bytes/string as-written.
  final Object? encodedBody;
  if (body == null) {
    encodedBody = null;
  } else if (bodyContentType == BodyContentType.json) {
    encodedBody = jsonEncode(body);
  } else {
    encodedBody = body;
  }
  final headers = _resolveHeaders(
    bodyContentType: body != null ? bodyContentType : null,
    headerParameters: headerParameters,
    auth: auth,
  );

  return _sendWithExceptionMapping(
    method: method,
    path: path,
    send: () => switch (method) {
      Method.delete => client.delete(uri, headers: headers),
      Method.get => client.get(uri, headers: headers),
      Method.patch => client.patch(uri, headers: headers, body: encodedBody),
      Method.post => client.post(uri, headers: headers, body: encodedBody),
      Method.put => client.put(uri, headers: headers, body: encodedBody),
    },
  );
}