From 756a1545511561b7b824501e338f34e2a246bea9 Mon Sep 17 00:00:00 2001 From: Tobe O Date: Tue, 15 May 2018 15:11:12 -0400 Subject: [PATCH] Check for required fields --- angel_serialize_generator/lib/build_context.dart | 13 +++++++++++++ angel_serialize_generator/lib/context.dart | 3 +++ angel_serialize_generator/pubspec.yaml | 1 + 3 files changed, 17 insertions(+) diff --git a/angel_serialize_generator/lib/build_context.dart b/angel_serialize_generator/lib/build_context.dart index 8b539d95..03b24132 100644 --- a/angel_serialize_generator/lib/build_context.dart +++ b/angel_serialize_generator/lib/build_context.dart @@ -4,6 +4,7 @@ import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:angel_serialize/angel_serialize.dart'; import 'package:build/build.dart'; +import 'package:meta/meta.dart'; import 'package:path/path.dart' as p; import 'package:recase/recase.dart'; import 'package:source_gen/source_gen.dart'; @@ -72,6 +73,18 @@ Future buildContext( ctx.aliases[field.name] = new ReCase(field.name).snakeCase; } + // Check for @required + var required = + const TypeChecker.fromRuntime(Required).firstAnnotationOf(el); + + if (required != null) { + var cr = new ConstantReader(required); + var reason = cr.peek('reason')?.stringValue ?? + "Missing field '${ctx.resolveFieldName(field.name)}' on ${ctx + .modelClassName}."; + ctx.requiredFields[field.name] = reason; + } + ctx.fields.add(field); } } diff --git a/angel_serialize_generator/lib/context.dart b/angel_serialize_generator/lib/context.dart index 70687761..7fd245a6 100644 --- a/angel_serialize_generator/lib/context.dart +++ b/angel_serialize_generator/lib/context.dart @@ -9,6 +9,9 @@ class BuildContext { ReCase _modelClassNameRecase; TypeReference _modelClassType; + /// A map of fields that are absolutely required, and error messages for when they are absent. + final Map requiredFields = {}; + /// A map of field names to resolved names from `@Alias()` declarations. final Map aliases = {}; diff --git a/angel_serialize_generator/pubspec.yaml b/angel_serialize_generator/pubspec.yaml index 4ef57d7f..4852d1a5 100644 --- a/angel_serialize_generator/pubspec.yaml +++ b/angel_serialize_generator/pubspec.yaml @@ -11,6 +11,7 @@ dependencies: code_buffer: ^1.0.0 code_builder: ^3.0.0 id: ^1.0.0 + meta: ^1.0.0 recase: ^1.0.0 source_gen: ^0.7.0 dev_dependencies: