From fbe03b8d0a75f0d4b20544886c1807c0799dd08d Mon Sep 17 00:00:00 2001 From: jld3103 Date: Wed, 11 Jan 2023 10:59:34 +0100 Subject: [PATCH] dynamite: Support strings with patterns --- packages/dynamite/lib/src/models/schema.dart | 3 +++ packages/dynamite/lib/src/models/schema.g.dart | 5 ++++- packages/dynamite/lib/src/openapi_builder.dart | 8 ++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/packages/dynamite/lib/src/models/schema.dart b/packages/dynamite/lib/src/models/schema.dart index ffd891a2..fb94b4c5 100644 --- a/packages/dynamite/lib/src/models/schema.dart +++ b/packages/dynamite/lib/src/models/schema.dart @@ -23,6 +23,7 @@ class Schema { this.contentMediaType, this.contentSchema, this.discriminator, + this.pattern, }); factory Schema.fromJson(final Map json) => _$SchemaFromJson(json); @@ -67,5 +68,7 @@ class Schema { final Discriminator? discriminator; + final String? pattern; + bool get isContentString => type == 'string' && (contentMediaType?.isNotEmpty ?? false) && contentSchema != null; } diff --git a/packages/dynamite/lib/src/models/schema.g.dart b/packages/dynamite/lib/src/models/schema.g.dart index a2e7b0cb..afd37486 100644 --- a/packages/dynamite/lib/src/models/schema.g.dart +++ b/packages/dynamite/lib/src/models/schema.g.dart @@ -26,7 +26,8 @@ Schema _$SchemaFromJson(Map json) { 'additionalProperties', 'contentMediaType', 'contentSchema', - 'discriminator' + 'discriminator', + 'pattern' ], ); return Schema( @@ -51,6 +52,7 @@ Schema _$SchemaFromJson(Map json) { json['contentSchema'] == null ? null : Schema.fromJson(json['contentSchema'] as Map), discriminator: json['discriminator'] == null ? null : Discriminator.fromJson(json['discriminator'] as Map), + pattern: json['pattern'] as String?, ); } @@ -80,5 +82,6 @@ Map _$SchemaToJson(Schema instance) { writeNotNull('contentMediaType', instance.contentMediaType); writeNotNull('contentSchema', instance.contentSchema?.toJson()); writeNotNull('discriminator', instance.discriminator?.toJson()); + writeNotNull('pattern', instance.pattern); return val; } diff --git a/packages/dynamite/lib/src/openapi_builder.dart b/packages/dynamite/lib/src/openapi_builder.dart index 9763e6b0..8a2e4e85 100644 --- a/packages/dynamite/lib/src/openapi_builder.dart +++ b/packages/dynamite/lib/src/openapi_builder.dart @@ -574,6 +574,14 @@ class OpenAPIBuilder implements Builder { parameter.schema!, ); + if (result.name == 'String' && 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 + } + '''); + } + final defaultValueCode = parameter.schema?.default_ != null ? _valueToEscapedValue(result.name, parameter.schema!.default_!.toString()) : null;