buildOperationRequest function

BaseRequest buildOperationRequest(
  1. Uri uri,
  2. Operation operation,
  3. Map<String, String> headers,
  4. Map<String, Object?>? body,
  5. List<OperationFile>? files,
)

The request of one attempt: a JSON, form or multipart body as the operation declares.

Implementation

http.BaseRequest buildOperationRequest(
  Uri uri,
  Operation operation,
  Map<String, String> headers,
  Map<String, Object?>? body,
  List<OperationFile>? files,
) {
  if (operation.body == OperationBody.multipart && (body != null || files != null)) {
    final request = http.MultipartRequest(operation.method, uri)..headers.addAll(headers);
    body?.forEach((key, value) {
      if (value == null) return;
      if (value is Iterable) {
        var i = 0;
        for (final item in value) {
          request.fields['$key[${i++}]'] = '$item';
        }
      } else {
        request.fields[key] = '$value';
      }
    });
    for (final file in files ?? const <OperationFile>[]) {
      request.files.add(http.MultipartFile.fromBytes(file.field, file.bytes, filename: file.filename));
    }
    return request;
  }
  final request = http.Request(operation.method, uri)..headers.addAll(headers);
  if (body != null && operation.body == OperationBody.form) {
    request.bodyFields = body.map((k, v) => MapEntry(k, '$v'))..removeWhere((k, v) => v == 'null');
  } else if (body != null && operation.body != OperationBody.none) {
    request.headers['Content-Type'] = 'application/json';
    request.body = jsonEncode(body);
  }
  return request;
}