platform/angel_serialize_generator/lib/context.dart

49 lines
1.7 KiB
Dart
Raw Normal View History

2017-06-20 22:13:04 +00:00
import 'package:analyzer/dart/element/element.dart';
2017-07-10 15:15:09 +00:00
import 'package:angel_serialize/angel_serialize.dart';
2018-02-27 20:03:58 +00:00
import 'package:code_builder/code_builder.dart';
2018-02-27 19:42:06 +00:00
import 'package:recase/recase.dart';
2017-06-20 22:13:04 +00:00
2018-02-27 19:20:39 +00:00
/// A base context for building serializable classes.
2017-06-20 22:13:04 +00:00
class BuildContext {
2018-02-27 19:42:06 +00:00
ReCase _modelClassNameRecase;
2018-02-27 20:03:58 +00:00
TypeReference _modelClassType;
2018-02-27 19:42:06 +00:00
2018-02-27 19:20:39 +00:00
/// A map of field names to resolved names from `@Alias()` declarations.
2017-06-20 22:13:04 +00:00
final Map<String, String> aliases = {};
2018-02-27 19:20:39 +00:00
/// A map of "synthetic" fields, i.e. `id` and `created_at` injected automatically.
2017-06-20 22:13:04 +00:00
final Map<String, bool> shimmed = {};
2018-02-27 19:20:39 +00:00
2017-06-20 22:13:04 +00:00
final String originalClassName, sourceFilename;
2018-02-27 19:20:39 +00:00
/// The fields declared on the original class.
2017-06-20 22:13:04 +00:00
final List<FieldElement> fields = [];
2018-02-27 19:20:39 +00:00
2017-06-20 22:13:04 +00:00
final Serializable annotation;
2018-02-27 19:20:39 +00:00
/// The name of the field that identifies data of this model type.
2017-06-20 22:13:04 +00:00
String primaryKeyName = 'id';
BuildContext(this.annotation, {this.originalClassName, this.sourceFilename});
2018-02-27 19:20:39 +00:00
/// The name of the generated class.
2017-06-20 22:13:04 +00:00
String get modelClassName => originalClassName.startsWith('_')
? originalClassName.substring(1)
: originalClassName;
2018-02-27 19:42:06 +00:00
/// A [ReCase] instance reflecting on the [modelClassName].
2018-02-27 20:03:58 +00:00
ReCase get modelClassNameRecase =>
_modelClassNameRecase ??= new ReCase(modelClassName);
TypeReference get modelClassType =>
_modelClassType ??= new TypeReference((b) => b.symbol = modelClassName);
2018-02-27 19:42:06 +00:00
2018-02-27 19:20:39 +00:00
/// The [FieldElement] pointing to the primary key.
FieldElement get primaryKeyField =>
fields.firstWhere((f) => f.name == primaryKeyName);
/// Get the aliased name (if one is defined) for a field.
2017-06-20 22:13:04 +00:00
String resolveFieldName(String name) =>
aliases.containsKey(name) ? aliases[name] : name;
}