Skip to content

Instantly share code, notes, and snippets.

@pingbird
Last active October 14, 2021 20:30
Show Gist options
  • Save pingbird/ad86b7b62995406c6915b17866644955 to your computer and use it in GitHub Desktop.
Save pingbird/ad86b7b62995406c6915b17866644955 to your computer and use it in GitHub Desktop.
import 'package:async/async.dart';
import 'package:chopper/chopper.dart' as chopper;
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:http/http.dart';
abstract class RequestCopier {
const RequestCopier._();
factory RequestCopier({
required BaseRequest original,
}) = _RequestCopierImpl;
BaseRequest copyRequest({
int? contentLength,
bool? followRedirects,
Map<String, String>? headers,
int? maxRedirects,
bool? persistentConnection,
});
}
class _RequestCopierImpl extends RequestCopier {
_RequestCopierImpl({required this.original})
: splitter = StreamSplitter(original.finalize()),
super._();
final BaseRequest original;
final StreamSplitter<List<int>> splitter;
@override
BaseRequest copyRequest({
Object? contentLength = freezed,
bool? followRedirects,
Map<String, String>? headers,
int? maxRedirects,
bool? persistentConnection,
}) {
final request = StreamedRequest(original.method, original.url)
..contentLength = contentLength == freezed
? original.contentLength
: contentLength as int?
..followRedirects = followRedirects ?? original.followRedirects
..headers.addAll(headers ?? original.headers)
..maxRedirects = maxRedirects ?? original.maxRedirects
..persistentConnection =
persistentConnection ?? original.persistentConnection;
splitter.split().listen(
request.sink.add,
onError: request.sink.addError,
onDone: request.sink.close,
cancelOnError: true,
);
return request;
}
}
class HttpException implements Exception {
const HttpException({
this.uri,
required this.statusCode,
required this.body,
});
factory HttpException.fromChopper(chopper.Response<Object?> response) {
final body = response.bodyString;
return HttpException(
uri: response.base.request?.url,
statusCode: response.statusCode,
body: body.isEmpty ? null : body,
);
}
static void ensureSuccess(chopper.Response<Object?> response) {
if (!response.isSuccessful) {
throw HttpException.fromChopper(response);
}
}
final Uri? uri;
final int statusCode;
final String? body;
@override
String toString() {
return 'HttpException: Error $statusCode${uri == null ? '' : ' from $uri'}'
'${body == null ? '' : ':\n$body'}';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment