Skip to content

Commit

Permalink
style: add trailing commas, reformat files.
Browse files Browse the repository at this point in the history
  • Loading branch information
hpoul committed May 14, 2024
1 parent 2d24334 commit 67ac40c
Show file tree
Hide file tree
Showing 12 changed files with 119 additions and 56 deletions.
2 changes: 2 additions & 0 deletions packages/openapi_base/analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,5 @@ analyzer:

linter:
rules:
unawaited_futures: true
require_trailing_commas: true
67 changes: 47 additions & 20 deletions packages/openapi_base/lib/src/openapi_base.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@ abstract class OpenApiRequest {
Future<Map<String, dynamic>> readJsonBody();

Future<Map<String, List<String>>> readUrlEncodedBody();

Future<Map<String, String>> readUrlEncodedBodyFlat() async =>
(await readUrlEncodedBody())
.map((key, value) => MapEntry(key, value.first));

Future<String> readBodyString();

Future<Uint8List> readBodyBytes();
}

Expand All @@ -44,6 +47,7 @@ abstract class OpenApiResponseBodyBinary {

abstract class OpenApiResponse {
int get status;

OpenApiContentType? get contentType;

// Map<String, dynamic> bodyJson;
Expand All @@ -70,12 +74,15 @@ typedef ApiEndpointCallback<ENDPOINT extends ApiEndpoint, RET> = Future<RET>

abstract class ApiEndpointProvider<ENDPOINT extends ApiEndpoint> {
ApiEndpointProvider();

factory ApiEndpointProvider.static(ENDPOINT endpoint) {
return StaticEndpointProvider(endpoint);
}

Future<RET> invoke<RET>(
OpenApiRequest request, ApiEndpointCallback<ENDPOINT, RET> callback);
OpenApiRequest request,
ApiEndpointCallback<ENDPOINT, RET> callback,
);
}

class StaticEndpointProvider<ENDPOINT extends ApiEndpoint>
Expand All @@ -85,8 +92,10 @@ class StaticEndpointProvider<ENDPOINT extends ApiEndpoint>
final ENDPOINT endpoint;

@override
Future<RET> invoke<RET>(OpenApiRequest request,
ApiEndpointCallback<ENDPOINT, RET> callback) async {
Future<RET> invoke<RET>(
OpenApiRequest request,
ApiEndpointCallback<ENDPOINT, RET> callback,
) async {
return await callback(endpoint);
}
}
Expand All @@ -111,26 +120,34 @@ abstract class OpenApiServerRouterBase {
RouteHandler handle, {
required List<SecurityRequirement> security,
}) {
configs.add(RouteConfig(path, operationFromString(operation), handle,
security: security));
configs.add(
RouteConfig(
path,
operationFromString(operation),
handle,
security: security,
),
);
}

@protected
T paramRequired<T>(
{required String name,
List<String>? value,
required T Function(List<String> value) decode}) {
T paramRequired<T>({
required String name,
List<String>? value,
required T Function(List<String> value) decode,
}) {
if (value == null || value.isEmpty) {
throw MissingParameterException(name);
}
return decode(value);
}

@protected
T? paramOpt<T>(
{required String name,
List<String>? value,
required T Function(List<String> value) decode}) {
T? paramOpt<T>({
required String name,
List<String>? value,
required T Function(List<String> value) decode,
}) {
if (value == null || value.isEmpty) {
return null;
}
Expand Down Expand Up @@ -173,7 +190,8 @@ enum Operation {
Map<String, Operation> _operationsMap() {
final index = Operation.get.toString().indexOf('.') + 1;
return Map.fromEntries(
Operation.values.map((e) => MapEntry(e.toString().substring(index), e)));
Operation.values.map((e) => MapEntry(e.toString().substring(index), e)),
);
}

final Map<String, Operation> _operations = _operationsMap();
Expand Down Expand Up @@ -201,11 +219,13 @@ class RouteConfig {

class SecurityRequirement {
SecurityRequirement({required this.schemes});

List<SecurityRequirementScheme> schemes;
}

class SecurityRequirementScheme {
SecurityRequirementScheme({required this.scheme, required this.scopes});

final SecurityScheme scheme;
final List<String> scopes;
}
Expand Down Expand Up @@ -234,13 +254,16 @@ class SecuritySchemeHttpData extends SecuritySchemeData {

class SecuritySchemeHttp extends SecurityScheme<SecuritySchemeHttpData> {
SecuritySchemeHttp({required this.scheme});

final SecuritySchemeHttpScheme scheme;
static const _headerName = 'Authorization';
static const _headerPrefix = 'Bearer ';

@override
void applyToRequest(
OpenApiClientRequest request, SecuritySchemeHttpData data) {
OpenApiClientRequest request,
SecuritySchemeHttpData data,
) {
request.addHeaderParameter(
_headerName,
['$_headerPrefix${data.bearerToken}'],
Expand All @@ -263,14 +286,16 @@ class SecuritySchemeHttp extends SecurityScheme<SecuritySchemeHttpData> {

class SecuritySchemeApiKeyData extends SecuritySchemeData {
SecuritySchemeApiKeyData({required this.apiKey});

final String apiKey;
}

class SecuritySchemeApiKey extends SecurityScheme<SecuritySchemeApiKeyData> {
SecuritySchemeApiKey(
{required this.name,
required this.writeToRequest,
required this.readFromRequest});
SecuritySchemeApiKey({
required this.name,
required this.writeToRequest,
required this.readFromRequest,
});

final String name;
final void Function(OpenApiClientRequest request, String value)
Expand All @@ -279,7 +304,9 @@ class SecuritySchemeApiKey extends SecurityScheme<SecuritySchemeApiKeyData> {

@override
void applyToRequest(
OpenApiClientRequest request, SecuritySchemeApiKeyData data) {
OpenApiClientRequest request,
SecuritySchemeApiKeyData data,
) {
writeToRequest(request, data.apiKey);
}

Expand Down
41 changes: 29 additions & 12 deletions packages/openapi_base/lib/src/openapi_client_base.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,25 @@ final _logger = Logger('openapi_client_base');
typedef ResponseMap<T, R> = R Function(T response);

typedef ResponseParser<T extends OpenApiResponse> = Future<T> Function(
OpenApiClientResponse response);
OpenApiClientResponse response,
);

/// Api sender implementing the actual HTTP protocol.
/// See [HttpRequestSender].
abstract class OpenApiRequestSender {
Future<OpenApiClientResponse> sendRequest(
Uri baseUri, OpenApiClientRequest request);
Uri baseUri,
OpenApiClientRequest request,
);
}

/// Api sender implementing the actual HTTP protocol.
/// See [HttpRequestSender].
abstract class OpenApiGetRequestSender extends OpenApiRequestSender {
Stream<OpenApiClientResponse> sendGet(
Uri baseUri, OpenApiClientRequest request);
Uri baseUri,
OpenApiClientRequest request,
);
}

mixin OpenApiUrlEncodeMixin {
Expand All @@ -52,7 +57,9 @@ abstract class OpenApiClient {
Map<SecurityScheme, SecuritySchemeData> get _securitySchemeData;

void setAuth<U extends SecuritySchemeData, T extends SecurityScheme<U>>(
T security, U data);
T security,
U data,
);
}

abstract class OpenApiClientBase
Expand All @@ -67,12 +74,16 @@ abstract class OpenApiClientBase

@override
void setAuth<U extends SecuritySchemeData, T extends SecurityScheme<U>>(
T security, U data) {
T security,
U data,
) {
_securitySchemeData[security] = data;
}

Future<T> sendRequest<T extends OpenApiResponse>(OpenApiClientRequest request,
Map<String, ResponseParser<T>> parserMap) async {
Future<T> sendRequest<T extends OpenApiResponse>(
OpenApiClientRequest request,
Map<String, ResponseParser<T>> parserMap,
) async {
for (final security in request.securityRequirement) {
for (final scheme in security.schemes) {
final data = _securitySchemeData[scheme.scheme];
Expand Down Expand Up @@ -100,8 +111,9 @@ abstract class OpenApiClientBase
}

Stream<T> sendGetRequest<T extends OpenApiResponse>(
OpenApiClientRequest request,
Map<String, ResponseParser<T>> parserMap) async* {
OpenApiClientRequest request,
Map<String, ResponseParser<T>> parserMap,
) async* {
final sender = requestSender;
if (sender is! OpenApiGetRequestSender) {
throw StateError('Require a OpenApiGetRequestSender');
Expand Down Expand Up @@ -212,8 +224,11 @@ class OpenApiClientRequest {
void addQueryParameter(String name, Iterable<String>? value) =>
_addParam(paramQuery, name, value);

void _addParam(Map<String, List<String>> paramMap, String name,
Iterable<String>? value) {
void _addParam(
Map<String, List<String>> paramMap,
String name,
Iterable<String>? value,
) {
// TODO add it, if it already exists?
if (value == null) {
return;
Expand Down Expand Up @@ -287,7 +302,9 @@ class HttpRequestSender extends OpenApiRequestSender {

@override
Future<OpenApiClientResponse> sendRequest(
Uri baseUri, OpenApiClientRequest request) async {
Uri baseUri,
OpenApiClientRequest request,
) async {
_client ??= clientCreator();

final uri = request.resolveUri(baseUri);
Expand Down
1 change: 1 addition & 0 deletions packages/openapi_base/lib/src/openapi_content_type.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class OpenApiContentType {
final String contentType;

bool get isString => contentType.startsWith('text/');

bool get isJson => contentType.startsWith(json.contentType);

static const allKnown = [json, html, urlencoded];
Expand Down
1 change: 1 addition & 0 deletions packages/openapi_base/lib/src/openapi_exception.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import 'package:openapi_base/openapi_base.dart';
/// in the OpenApi yaml file.
abstract class OpenApiResponseException implements Exception {
int get status;

String get message;

@override
Expand Down
23 changes: 16 additions & 7 deletions packages/openapi_base/lib/src/server/openapi_shelf_server.dart
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,15 @@ class OpenApiShelfServer extends OpenApiServerBase {
bool shared = false,
String? poweredByHeader = 'Dart with package:shelf',
}) async {
final server = await io.serve(preparePipeline(), address, port,
securityContext: securityContext,
backlog: backlog,
shared: shared,
poweredByHeader: poweredByHeader);
final server = await io.serve(
preparePipeline(),
address,
port,
securityContext: securityContext,
backlog: backlog,
shared: shared,
poweredByHeader: poweredByHeader,
);
_logger
.info('Serving at http${''}://${server.address.host}:${server.port}');
return StoppableProcess((reason) async {
Expand All @@ -66,7 +70,10 @@ class OpenApiShelfServer extends OpenApiServerBase {
return await innerHandler(request);
} on OpenApiResponseException catch (e, stackTrace) {
_logger.fine(
'response exception during request handling', e, stackTrace);
'response exception during request handling',
e,
stackTrace,
);
return shelf.Response(e.status, body: e.message);
} catch (e, stackTrace) {
_logger.warning('Error while handling request.', e, stackTrace);
Expand All @@ -75,6 +82,7 @@ class OpenApiShelfServer extends OpenApiServerBase {
};
};
}

//
// Future<shelf.Response> _handleRequestWithExceptions(
// shelf.Request request) async {
Expand Down Expand Up @@ -137,7 +145,7 @@ class OpenApiShelfServer extends OpenApiServerBase {
...response.headers.map((key, value) => MapEntry(key, value.first)),
if (contentType != null) ...{
HttpHeaders.contentTypeHeader: contentType.toString(),
}
},
},
);

Expand All @@ -153,6 +161,7 @@ class ShelfRequest extends OpenApiRequest {
.map((key, value) => MapEntry(key, Uri.decodeComponent(value!)));

final shelf.Request _request;

// ignore: unused_field
final UriMatch _match;
final Map<String, String> _matchParametersDecoded;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class StoppableProcess extends StoppableProcessBase {
}

for (final sub in _listeners) {
sub.cancel();
await sub.cancel();
}
await _stop(reason ?? 'Terminated normally.');
_completer.complete(exitCode);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ class CookieParser {
/// Factory constructor to create a new instance from request [headers].
factory CookieParser.fromHeader(Map<String, dynamic> headers) {
return CookieParser.fromCookieValue(
headers[HttpHeaders.cookieHeader] as String?);
headers[HttpHeaders.cookieHeader] as String?,
);
}

/// A list of parsed cookies.
Expand Down
23 changes: 13 additions & 10 deletions packages/openapi_base/lib/src/util/shelf_cookie/shelf_cookie.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,19 @@ shelf.Middleware cookieParser() {
return innerHandler(
request.change(context: {'cookies': cookies}),
);
}).then((shelf.Response response) {
if (cookies.isEmpty) {
return response;
}
return response.change(
headers: {HttpHeaders.setCookieHeader: cookies.toString()},
);
}, onError: (Object error, StackTrace stackTrace) {
throw error;
});
}).then(
(shelf.Response response) {
if (cookies.isEmpty) {
return response;
}
return response.change(
headers: {HttpHeaders.setCookieHeader: cookies.toString()},
);
},
onError: (Object error, StackTrace stackTrace) {
throw error;
},
);
};
};
}
Loading

0 comments on commit 67ac40c

Please sign in to comment.