From 6fbe4131054ecfb2921c46800d283204cd8677d0 Mon Sep 17 00:00:00 2001 From: Nikolas Rimikis Date: Sat, 2 Sep 2023 20:32:47 +0200 Subject: [PATCH] refactor(dynamite): unify code generation Signed-off-by: Nikolas Rimikis --- .../dynamite/lib/src/builder/client.dart | 110 +++++++++--------- .../lib/src/builder/header_serializer.dart | 40 +++---- 2 files changed, 75 insertions(+), 75 deletions(-) diff --git a/packages/dynamite/dynamite/lib/src/builder/client.dart b/packages/dynamite/dynamite/lib/src/builder/client.dart index 3cd92687..cfac493f 100644 --- a/packages/dynamite/dynamite/lib/src/builder/client.dart +++ b/packages/dynamite/dynamite/lib/src/builder/client.dart @@ -79,20 +79,20 @@ List generateDynamiteOverrides(final State state) => [ ..type = refer('HttpClientResponse'), ), ) - ..body = Block.of([ - const Code('String body;'), - const Code('try {'), - const Code('body = await response.body;'), - const Code('} on FormatException {'), - const Code("body = 'binary';"), - const Code('}'), - const Code(''), - Code('return ${state.classPrefix}ApiException('), - const Code('response.statusCode,'), - const Code('response.responseHeaders,'), - const Code('body,'), - const Code(');'), - ]), + ..body = Code(''' +String body; +try { + body = await response.body; +} on FormatException { + body = 'binary'; +} + +return ${state.classPrefix}ApiException( + response.statusCode, + response.responseHeaders, + body, +); +'''), ), Method( (final b) => b @@ -190,14 +190,14 @@ Class buildRootClient( ) ..initializers.add( const Code(''' - super( - client.baseURL, - baseHeaders: client.baseHeaders, - httpClient: client.httpClient, - cookieJar: client.cookieJar, - authentications: client.authentications, - ) - '''), +super( + client.baseURL, + baseHeaders: client.baseHeaders, + httpClient: client.httpClient, + cookieJar: client.cookieJar, + authentications: client.authentications, +) +'''), ), ), ]); @@ -305,11 +305,11 @@ Iterable buildTags( .join(',') ?? ''; final code = StringBuffer(''' - var _path = '${pathEntry.key}'; - final _queryParameters = {}; - final _headers = {${acceptHeader.isNotEmpty ? "'Accept': '$acceptHeader'," : ''}}; - Uint8List? _body; - '''); +var _path = '${pathEntry.key}'; +final _queryParameters = {}; +final _headers = {${acceptHeader.isNotEmpty ? "'Accept': '$acceptHeader'," : ''}}; +Uint8List? _body; +'''); final security = operation.security ?? spec.security ?? []; final securityRequirements = security.where((final requirement) => requirement.isNotEmpty); @@ -318,20 +318,20 @@ Iterable buildTags( for (final requirement in securityRequirements) { final securityScheme = spec.components!.securitySchemes![requirement.keys.single]!; code.write(''' - if (${isRootClient ? 'this' : '_rootClient'}.authentications.where((final a) => a.type == '${securityScheme.type}' && a.scheme == '${securityScheme.scheme}').isNotEmpty) { - _headers.addAll(${isRootClient ? 'this' : '_rootClient'}.authentications.singleWhere((final a) => a.type == '${securityScheme.type}' && a.scheme == '${securityScheme.scheme}').headers); - } - '''); +if (${isRootClient ? 'this' : '_rootClient'}.authentications.where((final a) => a.type == '${securityScheme.type}' && a.scheme == '${securityScheme.scheme}').isNotEmpty) { + _headers.addAll(${isRootClient ? 'this' : '_rootClient'}.authentications.singleWhere((final a) => a.type == '${securityScheme.type}' && a.scheme == '${securityScheme.scheme}').headers); +} +'''); if (securityRequirements.last != requirement) { - code.write('else'); + code.write('else '); } } if (securityRequirements.isNotEmpty && !isOptionalSecurity) { code.write(''' - else { - throw Exception('Missing authentication for ${securityRequirements.map((final r) => r.keys.single).join(' or ')}'); - } - '''); +else { + throw Exception('Missing authentication for ${securityRequirements.map((final r) => r.keys.single).join(' or ')}'); +} +'''); } code.write(' // coverage:ignore-end\n'); @@ -355,24 +355,24 @@ Iterable buildTags( if (result.name == 'String') { if (parameter.schema?.pattern != null) { code.write(''' - if (!RegExp(r'${parameter.schema!.pattern!}').hasMatch(${toDartName(parameter.name)})) { - throw Exception('Invalid value "\$${toDartName(parameter.name)}" for parameter "${toDartName(parameter.name)}" with pattern "\${r'${parameter.schema!.pattern!}'}"'); // coverage:ignore-line - } - '''); +if (!RegExp(r'${parameter.schema!.pattern!}').hasMatch(${toDartName(parameter.name)})) { + throw Exception('Invalid value "\$${toDartName(parameter.name)}" for parameter "${toDartName(parameter.name)}" with pattern "\${r'${parameter.schema!.pattern!}'}"'); // coverage:ignore-line +} +'''); } if (parameter.schema?.minLength != null) { code.write(''' - if (${toDartName(parameter.name)}.length < ${parameter.schema!.minLength!}) { - throw Exception('Parameter "${toDartName(parameter.name)}" has to be at least ${parameter.schema!.minLength!} characters long'); // coverage:ignore-line - } - '''); +if (${toDartName(parameter.name)}.length < ${parameter.schema!.minLength!}) { + throw Exception('Parameter "${toDartName(parameter.name)}" has to be at least ${parameter.schema!.minLength!} characters long'); // coverage:ignore-line +} +'''); } if (parameter.schema?.maxLength != null) { code.write(''' - if (${toDartName(parameter.name)}.length > ${parameter.schema!.maxLength!}) { - throw Exception('Parameter "${toDartName(parameter.name)}" has to be at most ${parameter.schema!.maxLength!} characters long'); // coverage:ignore-line - } - '''); +if (${toDartName(parameter.name)}.length > ${parameter.schema!.maxLength!}) { + throw Exception('Parameter "${toDartName(parameter.name)}" has to be at most ${parameter.schema!.maxLength!} characters long'); // coverage:ignore-line +} +'''); } } @@ -488,13 +488,13 @@ Iterable buildTags( code.write( ''' - final _response = await ${isRootClient ? 'this' : '_rootClient'}.doRequest( - '$httpMethod', - Uri(path: _path, queryParameters: _queryParameters.isNotEmpty ? _queryParameters : null), - _headers, - _body, - ); - ''', +final _response = await ${isRootClient ? 'this' : '_rootClient'}.doRequest( + '$httpMethod', + Uri(path: _path, queryParameters: _queryParameters.isNotEmpty ? _queryParameters : null), + _headers, + _body, +); +''', ); if (operation.responses != null) { diff --git a/packages/dynamite/dynamite/lib/src/builder/header_serializer.dart b/packages/dynamite/dynamite/lib/src/builder/header_serializer.dart index ce8c8d92..0a6f519b 100644 --- a/packages/dynamite/dynamite/lib/src/builder/header_serializer.dart +++ b/packages/dynamite/dynamite/lib/src/builder/header_serializer.dart @@ -85,26 +85,26 @@ Spec buildHeaderSerializer(final State state, final String identifier, final Ope ..defaultTo = const Code('FullType.unspecified'), ), ) - ..body = Block.of([ - Code('final result = new ${state.classPrefix}${identifier}Builder();'), - const Code(''), - const Code('final iterator = serialized.iterator;'), - const Code('while (iterator.moveNext()) {'), - const Code('final key = iterator.current! as String;'), - const Code('iterator.moveNext();'), - const Code('final value = iterator.current! as String;'), - const Code('switch (key) {'), - ...deserializeProperty(state, identifier, spec, schema), - const Code('}'), - const Code('}'), - const Code(''), - const Code('return result.build();'), - ]); + ..body = Code(''' +final result = new ${state.classPrefix}${identifier}Builder(); + +final iterator = serialized.iterator; +while (iterator.moveNext()) { + final key = iterator.current! as String; + iterator.moveNext(); + final value = iterator.current! as String; + switch (key) { + ${deserializeProperty(state, identifier, spec, schema).join('\n')} + } +} + +return result.build(); +'''); }), ]), ); -Iterable deserializeProperty( +Iterable deserializeProperty( final State state, final String identifier, final OpenAPI spec, @@ -121,15 +121,15 @@ Iterable deserializeProperty( nullable: isDartParameterNullable(schema.required?.contains(propertyName), propertySchema), ); - yield Code("case '$propertyName':"); + yield "case '$propertyName':"; if (result.className != 'String') { if (result is TypeResultBase || result is TypeResultEnum) { - yield Code('result.${toDartName(propertyName)} = ${result.deserialize(result.decode('value!'))};'); + yield 'result.${toDartName(propertyName)} = ${result.deserialize(result.decode('value!'))};'; } else { - yield Code('result.${toDartName(propertyName)}.replace(${result.deserialize(result.decode('value!'))});'); + yield 'result.${toDartName(propertyName)}.replace(${result.deserialize(result.decode('value!'))});'; } } else { - yield Code('result.${toDartName(propertyName)} = value!;'); + yield 'result.${toDartName(propertyName)} = value!;'; } } }