Last active
October 14, 2021 20:30
-
-
Save pingbird/ad86b7b62995406c6915b17866644955 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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