refactor(http)!: fix cascade dart good practices + docs
This commit is contained in:
@@ -18,12 +18,21 @@ import 'package:wyatt_http_client/src/models/middleware_context.dart';
|
||||
import 'package:wyatt_http_client/src/models/middleware_request.dart';
|
||||
import 'package:wyatt_http_client/src/models/middleware_response.dart';
|
||||
|
||||
/// {@template middleware}
|
||||
/// A middleware is a class that can intercept requests and responses
|
||||
/// and modify them before they are sent to the server or before they
|
||||
/// are returned to the client.
|
||||
/// {@endtemplate}
|
||||
abstract class Middleware {
|
||||
Middleware();
|
||||
/// {@macro middleware}
|
||||
const Middleware();
|
||||
|
||||
/// The name of the middleware.
|
||||
String getName();
|
||||
}
|
||||
|
||||
mixin OnRequestMiddleware {
|
||||
/// Performs an action before the request is sent to the server.
|
||||
Future<MiddlewareRequest> onRequest(
|
||||
MiddlewareContext context,
|
||||
MiddlewareRequest request,
|
||||
@@ -31,6 +40,7 @@ mixin OnRequestMiddleware {
|
||||
}
|
||||
|
||||
mixin OnResponseMiddleware {
|
||||
/// Performs an action before the response is returned to the client.
|
||||
Future<MiddlewareResponse> onResponse(
|
||||
MiddlewareContext context,
|
||||
MiddlewareResponse response,
|
||||
|
||||
@@ -24,15 +24,23 @@ import 'package:wyatt_http_client/src/models/unfreezed_request.dart';
|
||||
import 'package:wyatt_http_client/src/pipeline.dart';
|
||||
import 'package:wyatt_http_client/src/utils/http_methods.dart';
|
||||
|
||||
/// {@template middleware_client}
|
||||
/// A custom [Client] implementation that allows you to intercept requests
|
||||
/// and responses and modify them before they are sent to the server or
|
||||
/// before they are returned to the client.
|
||||
/// {@endtemplate}
|
||||
class MiddlewareClient extends BaseClient {
|
||||
/// {@macro middleware_client}
|
||||
MiddlewareClient({
|
||||
Pipeline? pipeline,
|
||||
Client? inner,
|
||||
}) : pipeline = pipeline ?? Pipeline(),
|
||||
inner = inner ?? Client() {
|
||||
print('Using Pipeline:\n$pipeline');
|
||||
}
|
||||
inner = inner ?? Client();
|
||||
|
||||
/// The [Client] that will be used to send requests.
|
||||
final Client inner;
|
||||
|
||||
/// The [Pipeline] that will be used to intercept requests and responses.
|
||||
final Pipeline pipeline;
|
||||
|
||||
@override
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
// Copyright (C) 2022 WYATT GROUP
|
||||
// Please see the AUTHORS file for details.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
@@ -22,14 +22,24 @@ import 'package:wyatt_http_client/src/models/middleware_request.dart';
|
||||
import 'package:wyatt_http_client/src/utils/authentication_methods.dart';
|
||||
import 'package:wyatt_http_client/src/utils/header_keys.dart';
|
||||
|
||||
/// {@template basic_auth_middleware}
|
||||
/// A middleware that adds basic authentication to the request.
|
||||
/// {@endtemplate}
|
||||
class BasicAuthMiddleware with OnRequestMiddleware implements Middleware {
|
||||
BasicAuthMiddleware({
|
||||
/// {@macro basic_auth_middleware}
|
||||
const BasicAuthMiddleware({
|
||||
this.username,
|
||||
this.password,
|
||||
this.authenticationHeader = HeaderKeys.authorization,
|
||||
});
|
||||
String? username;
|
||||
String? password;
|
||||
|
||||
/// The username to use for authentication.
|
||||
final String? username;
|
||||
|
||||
/// The password to use for authentication.
|
||||
final String? password;
|
||||
|
||||
/// The header to use for authentication.
|
||||
final String authenticationHeader;
|
||||
|
||||
@override
|
||||
@@ -43,10 +53,7 @@ class BasicAuthMiddleware with OnRequestMiddleware implements Middleware {
|
||||
if (username == null || password == null) {
|
||||
return request;
|
||||
}
|
||||
print(
|
||||
'${getName()}::OnRequest\n'
|
||||
'>> Basic: ${base64Encode(utf8.encode('$username:$password'))}',
|
||||
);
|
||||
|
||||
final mutation = {
|
||||
authenticationHeader: '${AuthenticationMethods.basic} '
|
||||
'${base64Encode(utf8.encode('$username:$password'))}',
|
||||
|
||||
@@ -20,7 +20,13 @@ import 'package:wyatt_http_client/src/middleware.dart';
|
||||
import 'package:wyatt_http_client/src/models/middleware_context.dart';
|
||||
import 'package:wyatt_http_client/src/models/middleware_request.dart';
|
||||
|
||||
/// {@template body_to_json_middleware}
|
||||
/// A middleware that transforms the body in json if it's a [Map].
|
||||
/// {@endtemplate}
|
||||
class BodyToJsonMiddleware with OnRequestMiddleware implements Middleware {
|
||||
/// {@macro body_to_json_middleware}
|
||||
const BodyToJsonMiddleware();
|
||||
|
||||
@override
|
||||
String getName() => 'BodyToJson';
|
||||
|
||||
@@ -29,11 +35,6 @@ class BodyToJsonMiddleware with OnRequestMiddleware implements Middleware {
|
||||
MiddlewareContext context,
|
||||
MiddlewareRequest request,
|
||||
) async {
|
||||
print(
|
||||
'${getName()}::OnRequest\n'
|
||||
'>> Transforms body in json if Map then update '
|
||||
'headers with right content-type',
|
||||
);
|
||||
final mutation = {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
};
|
||||
|
||||
@@ -16,7 +16,13 @@
|
||||
|
||||
import 'package:wyatt_http_client/src/middleware.dart';
|
||||
|
||||
/// {@template default_middleware}
|
||||
/// A default middleware that does nothing.
|
||||
/// {@endtemplate}
|
||||
class DefaultMiddleware implements Middleware {
|
||||
/// {@macro default_middleware}
|
||||
const DefaultMiddleware();
|
||||
|
||||
@override
|
||||
String getName() => 'DefaultMiddleware';
|
||||
}
|
||||
|
||||
@@ -22,9 +22,13 @@ import 'package:wyatt_http_client/src/utils/digest_auth.dart';
|
||||
import 'package:wyatt_http_client/src/utils/header_keys.dart';
|
||||
import 'package:wyatt_http_client/src/utils/http_status.dart';
|
||||
|
||||
/// {@template digest_auth_middleware}
|
||||
/// A middleware that handles digest authentication.
|
||||
/// {@endtemplate}
|
||||
class DigestAuthMiddleware
|
||||
with OnRequestMiddleware, OnResponseMiddleware
|
||||
implements Middleware {
|
||||
/// {@macro digest_auth_middleware}
|
||||
DigestAuthMiddleware({
|
||||
required this.username,
|
||||
required this.password,
|
||||
@@ -47,10 +51,6 @@ class DigestAuthMiddleware
|
||||
MiddlewareContext context,
|
||||
MiddlewareRequest request,
|
||||
) async {
|
||||
print(
|
||||
'${getName()}::OnRequest\n'
|
||||
'>> Digest ready: ${_digestAuth.isReady()}',
|
||||
);
|
||||
if (_digestAuth.isReady()) {
|
||||
final mutation = {
|
||||
authenticationHeader: _digestAuth.getAuthString(
|
||||
@@ -82,10 +82,6 @@ class DigestAuthMiddleware
|
||||
return MiddlewareResponse(httpResponse: newResponse);
|
||||
}
|
||||
}
|
||||
print(
|
||||
'${getName()}::OnResponse\n'
|
||||
'>> Digest ready: ${_digestAuth.isReady()}',
|
||||
);
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
export 'access_token_auth_middleware.dart';
|
||||
// All built-in middlewares
|
||||
|
||||
export 'basic_auth_middleware.dart';
|
||||
export 'body_to_json_middleware.dart';
|
||||
export 'default_middleware.dart';
|
||||
|
||||
@@ -28,9 +28,14 @@ import 'package:wyatt_http_client/src/utils/http_status.dart';
|
||||
|
||||
typedef TokenParser = String Function(Map<String, dynamic>);
|
||||
|
||||
/// {@template refresh_token_auth_middleware}
|
||||
/// A middleware that refreshes the access token when it expires.
|
||||
/// This middleware is useful for OAuth2.
|
||||
/// {@endtemplate}
|
||||
class RefreshTokenAuthMiddleware
|
||||
with OnRequestMiddleware, OnResponseMiddleware
|
||||
implements Middleware {
|
||||
/// {@macro refresh_token_auth_middleware}
|
||||
RefreshTokenAuthMiddleware({
|
||||
required this.authorizationEndpoint,
|
||||
required this.tokenEndpoint,
|
||||
@@ -113,11 +118,6 @@ class RefreshTokenAuthMiddleware
|
||||
MiddlewareContext context,
|
||||
MiddlewareRequest request,
|
||||
) async {
|
||||
print(
|
||||
'${getName()}::OnRequest\n'
|
||||
'>> accessToken: $accessToken\n'
|
||||
'>> refreshToken: $refreshToken',
|
||||
);
|
||||
// Check if it is authorization
|
||||
if (context.originalRequest?.url == Uri.parse(authorizationEndpoint)) {
|
||||
return request;
|
||||
@@ -168,12 +168,6 @@ class RefreshTokenAuthMiddleware
|
||||
}
|
||||
}
|
||||
|
||||
print(
|
||||
'${getName()}::OnResponse\n'
|
||||
'>> accessToken: $accessToken\n'
|
||||
'>> refreshToken: $refreshToken',
|
||||
);
|
||||
|
||||
if (response.status == unauthorized) {
|
||||
// Refresh
|
||||
MiddlewareRequest? newRequest = await refresh(context);
|
||||
|
||||
@@ -19,9 +19,15 @@ import 'package:wyatt_http_client/src/models/middleware_context.dart';
|
||||
import 'package:wyatt_http_client/src/models/middleware_request.dart';
|
||||
import 'package:wyatt_http_client/src/models/middleware_response.dart';
|
||||
|
||||
/// {@template simple_logger_middleware}
|
||||
/// A simple logger middleware that logs the request and response.
|
||||
/// {@endtemplate}
|
||||
class SimpleLoggerMiddleware
|
||||
with OnRequestMiddleware, OnResponseMiddleware
|
||||
implements Middleware {
|
||||
/// {@macro simple_logger_middleware}
|
||||
const SimpleLoggerMiddleware();
|
||||
|
||||
@override
|
||||
String getName() => 'SimpleLogger';
|
||||
|
||||
@@ -30,11 +36,22 @@ class SimpleLoggerMiddleware
|
||||
MiddlewareContext context,
|
||||
MiddlewareRequest request,
|
||||
) async {
|
||||
print(
|
||||
'${getName()}::OnRequest\n'
|
||||
'>> ${request.method} ${request.url}\n'
|
||||
'>> Headers: ${request.headers}\n>> Body: ${request.encodedBody}',
|
||||
);
|
||||
final log = StringBuffer()
|
||||
..writeln('${getName()}::OnRequest')
|
||||
..writeln('>> ${request.method} ${request.url}');
|
||||
if (request.headers.isNotEmpty) {
|
||||
log.writeln('>> Headers:');
|
||||
request.headers.forEach((key, value) {
|
||||
log.writeln('>> $key: $value');
|
||||
});
|
||||
}
|
||||
if (request.encodedBody.isNotEmpty) {
|
||||
log
|
||||
..writeln('>> Body:')
|
||||
..writeln(request.encodedBody);
|
||||
}
|
||||
print(log);
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
@@ -43,12 +60,13 @@ class SimpleLoggerMiddleware
|
||||
MiddlewareContext context,
|
||||
MiddlewareResponse response,
|
||||
) async {
|
||||
print(
|
||||
'${getName()}::OnResponse\n'
|
||||
'>> Status: ${response.status.name.toUpperCase()}\n'
|
||||
'>> Length: ${response.contentLength ?? '0'} bytes',
|
||||
// '>> Body: ${response.body}',
|
||||
);
|
||||
final log = StringBuffer()
|
||||
..writeln('${getName()}::OnResponse')
|
||||
..writeln('>> Status: ${response.status.name.toUpperCase()}')
|
||||
..writeln('>> Length: ${response.contentLength ?? '0'} bytes');
|
||||
|
||||
print(log);
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,15 +19,20 @@ import 'package:wyatt_http_client/src/models/middleware_context.dart';
|
||||
import 'package:wyatt_http_client/src/models/middleware_request.dart';
|
||||
import 'package:wyatt_http_client/src/utils/convert.dart';
|
||||
|
||||
/// {@template unsafe_auth_middleware}
|
||||
/// A middleware that appends the username and password to the URL.
|
||||
///
|
||||
/// This is not recommended to use in production.
|
||||
/// {@endtemplate}
|
||||
class UnsafeAuthMiddleware with OnRequestMiddleware implements Middleware {
|
||||
UnsafeAuthMiddleware({
|
||||
const UnsafeAuthMiddleware({
|
||||
this.username,
|
||||
this.password,
|
||||
this.usernameField = 'username',
|
||||
this.passwordField = 'password',
|
||||
});
|
||||
String? username;
|
||||
String? password;
|
||||
final String? username;
|
||||
final String? password;
|
||||
|
||||
final String usernameField;
|
||||
final String passwordField;
|
||||
@@ -45,10 +50,6 @@ class UnsafeAuthMiddleware with OnRequestMiddleware implements Middleware {
|
||||
}
|
||||
final Uri uri =
|
||||
request.url + '?$usernameField=$username&$passwordField=$password';
|
||||
print(
|
||||
'${getName()}::OnRequest\n'
|
||||
'>> Append: ?$usernameField=$username&$passwordField=$password',
|
||||
);
|
||||
request.modifyRequest(request.unfreezedRequest.copyWith(url: uri));
|
||||
return request;
|
||||
}
|
||||
|
||||
@@ -19,12 +19,20 @@ import 'package:wyatt_http_client/src/models/middleware_context.dart';
|
||||
import 'package:wyatt_http_client/src/models/middleware_request.dart';
|
||||
import 'package:wyatt_http_client/src/utils/protocols.dart';
|
||||
|
||||
/// {@template uri_prefix_middleware}
|
||||
/// A middleware that adds a prefix to the request's URI.
|
||||
/// {@endtemplate}
|
||||
class UriPrefixMiddleware with OnRequestMiddleware implements Middleware {
|
||||
UriPrefixMiddleware({
|
||||
/// {@macro uri_prefix_middleware}
|
||||
const UriPrefixMiddleware({
|
||||
required this.protocol,
|
||||
required this.authority,
|
||||
});
|
||||
|
||||
/// The protocol of the prefix.
|
||||
final Protocols protocol;
|
||||
|
||||
/// The authority of the prefix.
|
||||
final String? authority;
|
||||
|
||||
@override
|
||||
@@ -36,11 +44,6 @@ class UriPrefixMiddleware with OnRequestMiddleware implements Middleware {
|
||||
MiddlewareRequest request,
|
||||
) async {
|
||||
final Uri uri = Uri.parse('${protocol.scheme}$authority${request.url}');
|
||||
print(
|
||||
'${getName()}::OnRequest\n'
|
||||
'>> From: ${request.url}\n'
|
||||
'>> To: $uri',
|
||||
);
|
||||
request.modifyRequest(request.unfreezedRequest.copyWith(url: uri));
|
||||
return request;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// ignore_for_file: public_member_api_docs, sort_constructors_first
|
||||
// Copyright (C) 2022 WYATT GROUP
|
||||
// Please see the AUTHORS file for details.
|
||||
//
|
||||
@@ -20,15 +19,12 @@ import 'package:wyatt_http_client/src/models/middleware_request.dart';
|
||||
import 'package:wyatt_http_client/src/models/middleware_response.dart';
|
||||
import 'package:wyatt_http_client/src/pipeline.dart';
|
||||
|
||||
/// {@template middleware_context}
|
||||
/// A class that contains the context of the middleware.
|
||||
/// {@endtemplate}
|
||||
class MiddlewareContext {
|
||||
Pipeline pipeline;
|
||||
MiddlewareClient client;
|
||||
MiddlewareRequest? originalRequest;
|
||||
MiddlewareRequest? lastRequest;
|
||||
MiddlewareResponse? originalResponse;
|
||||
MiddlewareResponse? lastResponse;
|
||||
|
||||
MiddlewareContext({
|
||||
/// {@macro middleware_context}
|
||||
const MiddlewareContext({
|
||||
required this.pipeline,
|
||||
required this.client,
|
||||
this.originalRequest,
|
||||
@@ -37,6 +33,26 @@ class MiddlewareContext {
|
||||
this.lastResponse,
|
||||
});
|
||||
|
||||
/// The pipeline that the middleware is in.
|
||||
final Pipeline pipeline;
|
||||
|
||||
/// The client that the middleware is in.
|
||||
final MiddlewareClient client;
|
||||
|
||||
/// The original request that the middleware is in.
|
||||
final MiddlewareRequest? originalRequest;
|
||||
|
||||
/// The last request that the middleware is in.
|
||||
final MiddlewareRequest? lastRequest;
|
||||
|
||||
/// The original response that the middleware is in.
|
||||
final MiddlewareResponse? originalResponse;
|
||||
|
||||
/// The last response that the middleware is in.
|
||||
final MiddlewareResponse? lastResponse;
|
||||
|
||||
/// Create a copy of this [MiddlewareContext] with the given fields replaced
|
||||
/// with the new values.
|
||||
MiddlewareContext copyWith({
|
||||
Pipeline? pipeline,
|
||||
MiddlewareClient? client,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// ignore_for_file: public_member_api_docs, sort_constructors_first
|
||||
// Copyright (C) 2022 WYATT GROUP
|
||||
// Please see the AUTHORS file for details.
|
||||
//
|
||||
@@ -22,24 +21,43 @@ import 'package:wyatt_http_client/src/models/unfreezed_request.dart';
|
||||
import 'package:wyatt_http_client/src/utils/convert.dart';
|
||||
import 'package:wyatt_http_client/src/utils/request_utils.dart';
|
||||
|
||||
/// {@template middleware_request}
|
||||
/// A class that represents a middleware request.
|
||||
/// {@endtemplate}
|
||||
class MiddlewareRequest {
|
||||
UnfreezedRequest unfreezedRequest;
|
||||
Request _httpRequest;
|
||||
|
||||
Request get request => _httpRequest;
|
||||
|
||||
// Proxy
|
||||
String get method => _httpRequest.method;
|
||||
Uri get url => _httpRequest.url;
|
||||
Map<String, String> get headers => _httpRequest.headers;
|
||||
Encoding get encoding => _httpRequest.encoding;
|
||||
String get encodedBody => _httpRequest.body;
|
||||
Object? get body => unfreezedRequest.body;
|
||||
|
||||
/// {@macro middleware_request}
|
||||
MiddlewareRequest({
|
||||
required this.unfreezedRequest,
|
||||
}) : _httpRequest = Request(unfreezedRequest.method, unfreezedRequest.url);
|
||||
|
||||
/// The unfreezed request.
|
||||
UnfreezedRequest unfreezedRequest;
|
||||
|
||||
Request _httpRequest;
|
||||
|
||||
/// The http request. (Read-only)
|
||||
Request get request => _httpRequest;
|
||||
|
||||
/// The request method (proxy, read-only).
|
||||
String get method => _httpRequest.method;
|
||||
|
||||
/// The request url (proxy, read-only).
|
||||
Uri get url => _httpRequest.url;
|
||||
|
||||
/// The request headers (proxy, read-only).
|
||||
Map<String, String> get headers => _httpRequest.headers;
|
||||
|
||||
/// The request body (proxy, read-only).
|
||||
Encoding get encoding => _httpRequest.encoding;
|
||||
|
||||
/// The request body (proxy, read-only).
|
||||
String get encodedBody => _httpRequest.body;
|
||||
|
||||
/// The request body (proxy, read-only).
|
||||
Object? get body => unfreezedRequest.body;
|
||||
|
||||
/// Copies this request and returns a new request with the given
|
||||
/// [unfreezedRequest].
|
||||
MiddlewareRequest copyWith({
|
||||
UnfreezedRequest? unfreezedRequest,
|
||||
}) =>
|
||||
@@ -47,6 +65,7 @@ class MiddlewareRequest {
|
||||
unfreezedRequest: unfreezedRequest ?? this.unfreezedRequest,
|
||||
);
|
||||
|
||||
/// Modifies the request with the given [unfreezedRequest].
|
||||
void modifyRequest(UnfreezedRequest unfreezedRequest) {
|
||||
String? body;
|
||||
if (unfreezedRequest.body != null) {
|
||||
@@ -72,6 +91,8 @@ class MiddlewareRequest {
|
||||
this.unfreezedRequest = unfreezedRequest;
|
||||
}
|
||||
|
||||
/// Applies the changes made to the request by modifying it with the
|
||||
/// [unfreezedRequest].
|
||||
void apply() {
|
||||
modifyRequest(unfreezedRequest);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// ignore_for_file: public_member_api_docs, sort_constructors_first
|
||||
// Copyright (C) 2022 WYATT GROUP
|
||||
// Please see the AUTHORS file for details.
|
||||
//
|
||||
@@ -18,12 +17,25 @@
|
||||
import 'package:http/http.dart';
|
||||
import 'package:wyatt_http_client/src/utils/http_status.dart';
|
||||
|
||||
/// {@template middleware_response}
|
||||
/// A class that represents a middleware response.
|
||||
/// {@endtemplate}
|
||||
class MiddlewareResponse {
|
||||
BaseResponse httpResponse;
|
||||
/// {@macro middleware_response}
|
||||
const MiddlewareResponse({
|
||||
required this.httpResponse,
|
||||
});
|
||||
|
||||
// Proxy
|
||||
/// {@macro middleware_response}
|
||||
final BaseResponse httpResponse;
|
||||
|
||||
/// The status code of the response. (proxy)
|
||||
int get statusCode => httpResponse.statusCode;
|
||||
|
||||
/// The status of the response. (proxy)
|
||||
HttpStatus get status => HttpStatus.from(statusCode);
|
||||
|
||||
/// The body of the response. (proxy or empty string)
|
||||
String get body {
|
||||
if (httpResponse is Response) {
|
||||
return (httpResponse as Response).body;
|
||||
@@ -32,13 +44,13 @@ class MiddlewareResponse {
|
||||
}
|
||||
}
|
||||
|
||||
/// The content length of the response. (proxy)
|
||||
int? get contentLength => httpResponse.contentLength;
|
||||
|
||||
/// The headers of the response. (proxy)
|
||||
Map<String, String> get headers => httpResponse.headers;
|
||||
|
||||
MiddlewareResponse({
|
||||
required this.httpResponse,
|
||||
});
|
||||
|
||||
/// Returns a copy of this response with the given [httpResponse].
|
||||
MiddlewareResponse copyWith({
|
||||
BaseResponse? httpResponse,
|
||||
}) =>
|
||||
|
||||
@@ -16,20 +16,38 @@
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
/// {@template unfreezed_request}
|
||||
/// A class that represents an unfreezed request.
|
||||
/// It is used to unfreeze a Request object, and allows you to
|
||||
/// modify the request before sending it.
|
||||
/// {@endtemplate}
|
||||
class UnfreezedRequest {
|
||||
UnfreezedRequest({
|
||||
/// {@macro unfreezed_request}
|
||||
const UnfreezedRequest({
|
||||
required this.method,
|
||||
required this.url,
|
||||
this.headers,
|
||||
this.body,
|
||||
this.encoding,
|
||||
});
|
||||
|
||||
/// The request method.
|
||||
final String method;
|
||||
|
||||
/// The request url.
|
||||
final Uri url;
|
||||
|
||||
/// The request headers.
|
||||
final Map<String, String>? headers;
|
||||
|
||||
/// The request body.
|
||||
final Object? body;
|
||||
|
||||
/// The request encoding.
|
||||
final Encoding? encoding;
|
||||
|
||||
/// Copies this request and returns a new request with the given [method],
|
||||
/// [url], [headers], [body] and [encoding].
|
||||
UnfreezedRequest copyWith({
|
||||
String? method,
|
||||
Uri? url,
|
||||
|
||||
@@ -19,20 +19,27 @@ import 'package:wyatt_http_client/src/models/middleware_context.dart';
|
||||
import 'package:wyatt_http_client/src/models/middleware_request.dart';
|
||||
import 'package:wyatt_http_client/src/models/middleware_response.dart';
|
||||
|
||||
/// {@template pipeline}
|
||||
/// A [Pipeline] is a list of [Middleware]s that are executed in order.
|
||||
/// {@endtemplate}
|
||||
class Pipeline {
|
||||
/// {@macro pipeline}
|
||||
Pipeline() : _middlewares = <Middleware>[];
|
||||
|
||||
/// {@macro pipeline}
|
||||
Pipeline.fromIterable(Iterable<Middleware> middlewares)
|
||||
: _middlewares = middlewares.toList();
|
||||
|
||||
final List<Middleware> _middlewares;
|
||||
|
||||
/// The length of the [Pipeline].
|
||||
///
|
||||
/// This is the number of [Middleware]s in the [Pipeline].
|
||||
int get length => _middlewares.length;
|
||||
|
||||
/// Add a [Middleware] to this [Pipeline]
|
||||
Pipeline addMiddleware(Middleware middleware) {
|
||||
void addMiddleware(Middleware middleware) {
|
||||
_middlewares.add(middleware);
|
||||
// TODO(hpcl): use Dart cascades instead of returning this
|
||||
// ignore: avoid_returning_this
|
||||
return this;
|
||||
}
|
||||
|
||||
/// Create new [Pipeline] from the start or end to a specified [Middleware].
|
||||
@@ -57,11 +64,15 @@ class Pipeline {
|
||||
return Pipeline.fromIterable(fromEnd ? nodes.reversed : nodes);
|
||||
}
|
||||
|
||||
/// Call the [onRequest] method of all [OnRequestMiddleware]s in the
|
||||
/// [Pipeline].
|
||||
///
|
||||
/// The [MiddlewareRequest] returned by the last [OnRequestMiddleware] is
|
||||
/// returned.
|
||||
Future<MiddlewareRequest> onRequest(
|
||||
MiddlewareContext context,
|
||||
MiddlewareRequest request,
|
||||
) async {
|
||||
print('\n\nNEW REQUEST\n');
|
||||
MiddlewareRequest req = request..apply();
|
||||
MiddlewareContext ctx = context.copyWith(lastRequest: req);
|
||||
for (final middleware in _middlewares) {
|
||||
@@ -73,11 +84,15 @@ class Pipeline {
|
||||
return req;
|
||||
}
|
||||
|
||||
/// Call the [onResponse] method of all [OnResponseMiddleware]s in the
|
||||
/// [Pipeline].
|
||||
///
|
||||
/// The [MiddlewareResponse] returned by the last [OnResponseMiddleware] is
|
||||
/// returned.
|
||||
Future<MiddlewareResponse> onResponse(
|
||||
MiddlewareContext context,
|
||||
MiddlewareResponse response,
|
||||
) async {
|
||||
print('\n\nNEW RESPONSE\n');
|
||||
MiddlewareResponse res = response;
|
||||
MiddlewareContext ctx = context.copyWith(lastResponse: res);
|
||||
for (final middleware in _middlewares.reversed) {
|
||||
|
||||
@@ -14,8 +14,14 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
/// Defines some authentication methods
|
||||
abstract class AuthenticationMethods {
|
||||
/// The `Basic` authentication method.
|
||||
static const String basic = 'Basic';
|
||||
|
||||
/// The `Bearer` authentication method.
|
||||
static const String bearer = 'Bearer';
|
||||
|
||||
/// The `Digest` authentication method.
|
||||
static const String digest = 'Digest';
|
||||
}
|
||||
|
||||
@@ -16,7 +16,11 @@
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
class Convert {
|
||||
/// Defines some convert functions.
|
||||
abstract class Convert {
|
||||
/// Converts a list of bytes to a hex string.
|
||||
///
|
||||
/// If [upperCase] is `true`, the hex string will be in uppercase.
|
||||
static String toHex(List<int> bytes, {bool upperCase = false}) {
|
||||
final buffer = StringBuffer();
|
||||
for (final int part in bytes) {
|
||||
@@ -32,6 +36,11 @@ class Convert {
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a map to a query string.
|
||||
///
|
||||
/// If [encoding] is `null`, the default encoding is `utf8`.
|
||||
///
|
||||
/// For example, the map `{a: 1, b: 2}` will be converted to `a=1&b=2`.
|
||||
static String mapToQuery(Map<String, String> map, {Encoding? encoding}) {
|
||||
final pairs = <List<String>>[];
|
||||
map.forEach(
|
||||
@@ -45,6 +54,7 @@ class Convert {
|
||||
}
|
||||
|
||||
extension UriX on Uri {
|
||||
/// Returns a new [Uri] by appending the given [path] to this [Uri].
|
||||
Uri operator +(String path) {
|
||||
final thisPath = toString();
|
||||
return Uri.parse(thisPath + path);
|
||||
|
||||
@@ -18,7 +18,8 @@ import 'dart:convert';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
||||
class Crypto {
|
||||
/// Defines some crypto functions.
|
||||
abstract class Crypto {
|
||||
/// Hash a string using MD5
|
||||
static String md5Hash(String data) {
|
||||
final content = const Utf8Encoder().convert(data);
|
||||
|
||||
@@ -17,7 +17,9 @@
|
||||
import 'dart:core';
|
||||
import 'dart:math';
|
||||
|
||||
/// Defines some delay functions.
|
||||
abstract class Delay {
|
||||
/// Returns a delay based on the [attempt].
|
||||
static Duration getRetryDelay(int attempt) {
|
||||
assert(attempt >= 0, 'attempt cannot be negative');
|
||||
if (attempt <= 0) {
|
||||
|
||||
@@ -19,12 +19,13 @@ import 'dart:math';
|
||||
import 'package:wyatt_http_client/src/utils/convert.dart';
|
||||
import 'package:wyatt_http_client/src/utils/crypto.dart';
|
||||
|
||||
/// A class for digest authentication.
|
||||
class DigestAuth {
|
||||
// request counter
|
||||
|
||||
DigestAuth(this.username, this.password);
|
||||
String username;
|
||||
String password;
|
||||
final String username;
|
||||
final String password;
|
||||
|
||||
// must get from first response
|
||||
String? _algorithm;
|
||||
|
||||
@@ -14,8 +14,14 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
/// Defines some header keys.
|
||||
abstract class HeaderKeys {
|
||||
/// The `Authorization` header key.
|
||||
static const String authorization = 'Authorization';
|
||||
|
||||
/// The `WWW-Authenticate` header key.
|
||||
static const String wwwAuthenticate = 'WWW-Authenticate';
|
||||
|
||||
/// The `Content-Type` header key.
|
||||
static const String contentType = 'Content-Type';
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
/// Defines http verb methods.
|
||||
enum HttpMethods {
|
||||
head('HEAD'),
|
||||
get('GET'),
|
||||
@@ -24,5 +25,8 @@ enum HttpMethods {
|
||||
|
||||
const HttpMethods(this.method);
|
||||
|
||||
/// Returns the method of the http verb.
|
||||
///
|
||||
/// For example, the method of [HttpMethods.get] is `GET`.
|
||||
final String method;
|
||||
}
|
||||
|
||||
@@ -83,6 +83,7 @@ enum HttpStatus {
|
||||
|
||||
const HttpStatus(this.statusCode);
|
||||
|
||||
/// Returns the [HttpStatus] with the given [statusCode].
|
||||
factory HttpStatus.from(int status) =>
|
||||
HttpStatus.values.firstWhere((element) => element.statusCode == status);
|
||||
|
||||
@@ -98,13 +99,18 @@ enum HttpStatus {
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Checks if the status code is in the range of 100-199.
|
||||
bool isInfo() => statusCode >= 100 && statusCode < 200;
|
||||
|
||||
/// Checks if the status code is in the range of 200-299.
|
||||
bool isSuccess() => statusCode >= 200 && statusCode < 300;
|
||||
|
||||
/// Checks if the status code is in the range of 300-399.
|
||||
bool isRedirection() => statusCode >= 300 && statusCode < 400;
|
||||
|
||||
/// Checks if the status code is in the range of 400-499.
|
||||
bool isClientError() => statusCode >= 400 && statusCode < 500;
|
||||
|
||||
/// Checks if the status code is in the range of 500-599.
|
||||
bool isServerError() => statusCode >= 500 && statusCode < 600;
|
||||
}
|
||||
|
||||
@@ -14,9 +14,13 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
/// Defines few protocols
|
||||
enum Protocols {
|
||||
http,
|
||||
https;
|
||||
|
||||
/// Returns the scheme of the protocol.
|
||||
///
|
||||
/// For example, the scheme of [Protocols.http] is `http://`.
|
||||
String get scheme => '$name://';
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
import 'package:http/http.dart';
|
||||
|
||||
/// Defines some request utils.
|
||||
abstract class RequestUtils {
|
||||
static Request _copyNormalRequestWith(
|
||||
Request original, {
|
||||
@@ -38,6 +39,9 @@ abstract class RequestUtils {
|
||||
return request;
|
||||
}
|
||||
|
||||
/// Copies the given [original] request and returns a new request with the
|
||||
/// given [method], [url], [headers], [maxRedirects], [followRedirects],
|
||||
/// [persistentConnection] and [body].
|
||||
static BaseRequest copyRequestWith(
|
||||
BaseRequest original, {
|
||||
String? method,
|
||||
@@ -77,6 +81,8 @@ abstract class RequestUtils {
|
||||
return request;
|
||||
}
|
||||
|
||||
/// Copies the given [original] request and returns a new request.
|
||||
/// This method is useful when you want to modify the request
|
||||
static BaseRequest copyRequest(BaseRequest original) {
|
||||
if (original is Request) {
|
||||
return _copyNormalRequest(original);
|
||||
|
||||
Reference in New Issue
Block a user