Skip to content

Commit

Permalink
#269 Support multiple UnionJsonKeyValue annotations for a factory
Browse files Browse the repository at this point in the history
  • Loading branch information
spideythewebhead committed Mar 30, 2023
1 parent 7080861 commit 2e2884b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
26 changes: 17 additions & 9 deletions package/lib/src/backend/core/generators/union_from_json.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,22 +38,30 @@ class UnionFromJsonGenerator implements Generator {
..writeln("switch (json['$unionJsonKey']) {");

for (final ConstructorDeclaration ctor in _factoriesWithRedirectedConstructors) {
String? jsonKeyValue =
AnnotationValueExtractor(ctor.metadata.getAnnotation(AnnotationType.unionJsonKeyValue))
.getPositionedArgument(0)
?.toSource();

if (ctor.name!.lexeme == unionFallbackJsonValue) {
defaultFallbackConstructor =
'${ctor.redirectedConstructor!.beginToken.lexeme}$_classTypeParametersSource';
// this will be included on the default branch
continue;
}

_codeWriter
..writeln('case ${jsonKeyValue ?? "'${ctor.name!.lexeme}'"}:')
..writeln(
'return ${ctor.redirectedConstructor!.beginToken.lexeme}$_classTypeParametersSource.fromJson(json);');
final List<Annotation> unionJsonKeyValueAnnotations =
ctor.metadata.getAllAnnotationsByType(AnnotationType.unionJsonKeyValue);
for (final Annotation annotation in unionJsonKeyValueAnnotations) {
final String? jsonKeyValue =
AnnotationValueExtractor(annotation).getPositionedArgument(0)?.toSource();
if (jsonKeyValue == null) {
continue;
}
_codeWriter.writeln('case $jsonKeyValue:');
}

if (unionJsonKeyValueAnnotations.isEmpty) {
_codeWriter.writeln("case '${ctor.name}':");
}

_codeWriter.writeln(
'return ${ctor.redirectedConstructor!.beginToken.lexeme}$_classTypeParametersSource.fromJson(json);');
}

if (unionFallbackJsonValue != null && defaultFallbackConstructor == null) {
Expand Down
4 changes: 4 additions & 0 deletions package/lib/src/extensions/annotation_extensions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ extension AnnotationNodeListX on NodeList<Annotation> {
return firstWhereOrNull((Annotation a) => a.name.name == annotation.name);
}

List<Annotation> getAllAnnotationsByType(AnnotationType annotation) {
return where((Annotation a) => a.name.name == annotation.name).toList(growable: false);
}

List<Annotation> get annotations {
return where((Annotation annotation) {
return AnnotationType.values
Expand Down

0 comments on commit 2e2884b

Please sign in to comment.