Add Http Request copyWith

This commit is contained in:
kodjomoustapha 2024-02-08 12:46:16 +01:00
parent 46b7f4d3c5
commit b42c5eba69
2 changed files with 30 additions and 7 deletions

View file

@ -26,8 +26,9 @@ class $Client implements $Instance {
constructors: {
'': BridgeConstructorDef(
BridgeFunctionDef(returns: BridgeTypeAnnotation($type), params: [
BridgeParameter(
'source', BridgeTypeAnnotation($MSource.$type), true),
BridgeParameter('source', BridgeTypeAnnotation($MSource.$type), true),
BridgeParameter('reqcopyWith',
BridgeTypeAnnotation(BridgeTypeRef(CoreTypes.string)), true),
], namedParams: []))
},
methods: {
@ -212,8 +213,12 @@ class $Client implements $Instance {
wrap: true);
static $Client $new(Runtime runtime, $Value? target, List<$Value?> args) {
final reqcopyWith = args[1]?.$value == null
? null
: (jsonDecode(args[1]!.$value) as Map)
.map((key, value) => MapEntry(key.toString(), value));
return $Client.wrap(
MInterceptor.init(source: args[0]?.$value),
MInterceptor.init(source: args[0]?.$value, reqcopyWith: reqcopyWith),
);
}

View file

@ -20,9 +20,10 @@ class MInterceptor {
MInterceptor();
static InterceptedClient init({MSource? source}) {
static InterceptedClient init(
{MSource? source, Map<String, dynamic>? reqcopyWith}) {
return InterceptedClient.build(interceptors: [
if (source?.hasCloudflare ?? false) ...[MCookieManager(_cookieJar)],
MCookieManager(_cookieJar, reqcopyWith),
LoggerInterceptor()
]);
}
@ -90,9 +91,10 @@ class MInterceptor {
}
class MCookieManager extends InterceptorContract {
MCookieManager(this.cookieJar);
MCookieManager(this.cookieJar, this.reqcopyWith);
Map<String, dynamic>? reqcopyWith;
final cookie_jar.CookieJar cookieJar;
static String getCookies(List<Cookie> cookies) {
cookies.sort((a, b) {
if (a.path == null && b.path == null) {
@ -125,6 +127,22 @@ class MCookieManager extends InterceptorContract {
request.headers[HttpHeaders.cookieHeader] =
newCookies.isNotEmpty ? newCookies : "";
request.headers[HttpHeaders.userAgentHeader] = userAgent;
try {
if (reqcopyWith != null) {
if (reqcopyWith!["followRedirects"] != null) {
request.followRedirects = reqcopyWith!["followRedirects"];
}
if (reqcopyWith!["maxRedirects"] != null) {
request.maxRedirects = reqcopyWith!["maxRedirects"];
}
if (reqcopyWith!["contentLength"] != null) {
request.contentLength = reqcopyWith!["contentLength"];
}
if (reqcopyWith!["persistentConnection"] != null) {
request.persistentConnection = reqcopyWith!["persistentConnection"];
}
}
} catch (_) {}
return request;
}