patch<T> method

Future<Either<ApiError, T>> patch<T>(
  1. String path,
  2. T conversionFunc(
    1. dynamic json
    ),
  3. {Map<String, String>? headers,
  4. Map<String, dynamic>? requestBody,
  5. Map<String, String>? queryParameters,
  6. Duration? timeoutDuration}
)

Perform a PATCH HTTP request

  • path is the endpoint of the request, it is added to the baseUrl of ApiBase

  • conversionFunc is a function used to transform the json (stored as a Map) into another object.

    Example of a conversionFunc for a example class:

    class Person {
      Person({required this.firstName, required this.lastName});
    
      String firstName;
      String lastName;
    }
    
    Person fromJsonToPerson(Map<String, dynamic> json) {
      return Person(firstName: json["firstName"], lastName: json["lastName"]);
    }
    
  • headers are a map of headers to add to the defaultHeaders, if a keys of headers is present in the defaultHeaders, its value is overridden by the one in headers. If the token of ApiBase has been set, an Authorization header will be added, it will override if a Authorization header has been set in the defaultHeaders but will be overriden if a Authorization header is present in the headers

  • requestBody is a Map<String, dynamic> containing the request body to send

  • queryParameters is a map containing the query parameters of the request

  • timeoutDuration is the Duration until a TimeoutException is thrown for the request. If not provided, the timeout duration is set to 10 seconds.

If the request is successful (status code 200), the Future returned by get will contain a right Either containing the data transformed into an object of type T by conversionFunc. Else, it will contain a left Either containing the a ApiError containing the status code and the body of the response as its message.

Implementation

Future<Either<ApiError, T>> patch<T>(
    String path, T Function(dynamic json) conversionFunc,
    {Map<String, String>? headers,
    Map<String, dynamic>? requestBody,
    Map<String, String>? queryParameters,
    Duration? timeoutDuration}) async {
  String? body = requestBody == null ? null : json.encode(requestBody);
  final promise = _client
      .patch(
        Uri.parse((_baseUrl ?? "") +
            path +
            (queryParameters?.entries
                    .map((entry) => "${entry.key}=${entry.value}")
                    .fold("?", (previous, current) {
                  if (previous == "?") {
                    return "?$current";
                  }
                  return "$previous&$current";
                }) ??
                "")),
        headers: <String, String>{
          ...?_defaultHeaders,
          if (_accessToken != null) "Authorization": "Bearer $_accessToken",
          ...?headers
        },
        body: body,
      )
      .timeout(timeoutDuration ?? const Duration(seconds: 60));
  return _handleApiResult(promise, path).mapRight(conversionFunc);
}