From ea298d43628d458721f4a27fd5360e10c3031522 Mon Sep 17 00:00:00 2001 From: Tobe O Date: Tue, 27 Feb 2018 20:49:14 -0500 Subject: [PATCH] Generate toJson() --- angel_serialize_generator/lib/model.dart | 17 +++++++++++++++-- .../test/models/author.g.dart | 8 ++++++++ .../test/models/book.g.dart | 4 ++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/angel_serialize_generator/lib/model.dart b/angel_serialize_generator/lib/model.dart index ed7e9b1d..aea27c87 100644 --- a/angel_serialize_generator/lib/model.dart +++ b/angel_serialize_generator/lib/model.dart @@ -15,7 +15,7 @@ class JsonModelGenerator extends GeneratorForAnnotation { await buildStep.resolver, true, autoIdAndDateFields != false); var lib = new File((b) { - generateClass(ctx, b); + generateClass(ctx, b, annotation); }); var buf = lib.accept(new DartEmitter()); @@ -23,7 +23,8 @@ class JsonModelGenerator extends GeneratorForAnnotation { } /// Generate an extended model class. - void generateClass(BuildContext ctx, FileBuilder file) { + void generateClass( + BuildContext ctx, FileBuilder file, ConstantReader annotation) { file.body.add(new Class((clazz) { clazz ..name = ctx.modelClassNameRecase.pascalCase @@ -42,6 +43,18 @@ class JsonModelGenerator extends GeneratorForAnnotation { generateConstructor(ctx, clazz, file); generateCopyWithMethod(ctx, clazz, file); + + // Generate toJson() method if necessary + var serializers = annotation.peek('serializers')?.listValue ?? []; + + if (serializers.any((o) => o.toIntValue() == Serializers.json)) { + clazz.methods.add(new Method((method) { + method + ..name = 'toJson' + ..returns = new Reference('Map') + ..body = new Code('return ${clazz.name}Serializer.toMap(this);'); + })); + } })); } diff --git a/angel_serialize_generator/test/models/author.g.dart b/angel_serialize_generator/test/models/author.g.dart index b95c10ac..228cf6a8 100644 --- a/angel_serialize_generator/test/models/author.g.dart +++ b/angel_serialize_generator/test/models/author.g.dart @@ -60,6 +60,10 @@ class Author extends _Author { createdAt: createdAt ?? this.createdAt, updatedAt: updatedAt ?? this.updatedAt); } + + Map toJson() { + return AuthorSerializer.toMap(this); + } } class Library extends _Library { @@ -88,4 +92,8 @@ class Library extends _Library { createdAt: createdAt ?? this.createdAt, updatedAt: updatedAt ?? this.updatedAt); } + + Map toJson() { + return LibrarySerializer.toMap(this); + } } diff --git a/angel_serialize_generator/test/models/book.g.dart b/angel_serialize_generator/test/models/book.g.dart index 5536383b..d6812325 100644 --- a/angel_serialize_generator/test/models/book.g.dart +++ b/angel_serialize_generator/test/models/book.g.dart @@ -54,4 +54,8 @@ class Book extends _Book { createdAt: createdAt ?? this.createdAt, updatedAt: updatedAt ?? this.updatedAt); } + + Map toJson() { + return BookSerializer.toMap(this); + } }