Added modelClassNameReCas

This commit is contained in:
Tobe O 2018-02-27 14:42:06 -05:00
parent 387f05009b
commit 50153dedf3
4 changed files with 59 additions and 2 deletions

View file

@ -0,0 +1,48 @@
library angel_serialize_generator;
import 'dart:async';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:angel_serialize/angel_serialize.dart';
import 'package:build/build.dart';
import 'package:code_builder/code_builder.dart';
import 'package:source_gen/source_gen.dart' hide LibraryBuilder;
import 'build_context.dart';
import 'context.dart';
part 'model.dart';
class JsonModelGenerator extends GeneratorForAnnotation<Serializable> {
final bool autoSnakeCaseNames;
final bool autoIdAndDateFields;
const JsonModelGenerator(
{this.autoSnakeCaseNames: true, this.autoIdAndDateFields: true});
@override
Future<String> generateForAnnotatedElement(Element element,
ConstantReader reader, BuildStep buildStep) async {
if (element.kind != ElementKind.CLASS)
throw 'Only classes can be annotated with a @Serializable() annotation.';
var ctx = await buildContext(
element,
serializable,
buildStep,
await buildStep.resolver,
autoSnakeCaseNames != false,
autoIdAndDateFields != false);
var lib = new File((b) {
generateClass(ctx, b);
});
var buf = lib.accept(new DartEmitter());
return buf.toString();
}
void generateClass(BuildContext ctx, FileBuilder file) {
file.body.add(new Class((clazz) {
}));
}
}

View file

@ -57,7 +57,8 @@ Future<BuildContext> buildContext(
if (autoIdAndDateFields != false) {
if (!fieldNames.contains('id')) {
var idField = new ShimFieldImpl('id', lib.context.typeProvider.stringType);
var idField =
new ShimFieldImpl('id', lib.context.typeProvider.stringType);
ctx.fields.insert(0, idField);
ctx.shimmed['id'] = true;
}
@ -78,7 +79,6 @@ Future<BuildContext> buildContext(
ctx.shimmed[key] = true;
}
}
;
}
return ctx;
@ -88,5 +88,6 @@ Future<BuildContext> buildContext(
class ShimFieldImpl extends FieldElementImpl {
@override
final DartType type;
ShimFieldImpl(String name, this.type) : super(name, -1);
}

View file

@ -1,8 +1,11 @@
import 'package:analyzer/dart/element/element.dart';
import 'package:angel_serialize/angel_serialize.dart';
import 'package:recase/recase.dart';
/// A base context for building serializable classes.
class BuildContext {
ReCase _modelClassNameRecase;
/// A map of field names to resolved names from `@Alias()` declarations.
final Map<String, String> aliases = {};
@ -26,6 +29,9 @@ class BuildContext {
? originalClassName.substring(1)
: originalClassName;
/// A [ReCase] instance reflecting on the [modelClassName].
ReCase get modelClassNameRecase => _modelClassNameRecase ??= new ReCase(modelClassName);
/// The [FieldElement] pointing to the primary key.
FieldElement get primaryKeyField =>
fields.firstWhere((f) => f.name == primaryKeyName);

View file

@ -0,0 +1,2 @@
part of angel_serialize_generator;