-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathenum_model_writer.dart
98 lines (85 loc) · 2.78 KB
/
enum_model_writer.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import 'package:model_generator/model/model/enum_model.dart';
import 'package:model_generator/util/model_helper.dart';
class EnumModelWriter {
final EnumModel jsonModel;
const EnumModelWriter(this.jsonModel);
String write() {
final sb = StringBuffer()
..writeln(ModelHelper.autoGeneratedWarning)
..writeln()
..writeln("import 'package:json_annotation/json_annotation.dart';")
..writeln();
final modelDescription = jsonModel.description?.trim();
if (modelDescription != null && modelDescription.isNotEmpty) {
sb.writeln("///$modelDescription");
}
sb.writeln('enum ${jsonModel.name} {');
var first = true;
jsonModel.fields?.forEach((key) {
final jsonValue = key.value == null || key.value?.isEmpty == null
? key.serializedName
: key.value;
final description = key.description;
if (first) {
first = false;
} else {
sb.writeln(',');
}
if (description != null) {
sb.writeln(' ///$description');
}
sb
..writeln(" @JsonValue('$jsonValue')")
..write(" ${key.name}('$jsonValue')");
});
if (jsonModel.fields?.isNotEmpty == true) {
sb.writeln(';');
}
sb.writeln('');
sb.writeln(' final String jsonValue;');
sb.writeln('');
sb.writeln(' const ${jsonModel.name}(this.jsonValue);');
sb.writeln('}');
if (jsonModel.generateMap) {
sb
..writeln()
..writeln('const ${jsonModel.name}Mapping = {');
jsonModel.fields?.forEach((key) {
final jsonValue = key.value == null || key.value?.isEmpty == null
? key.serializedName
: key.value;
sb
..write(' ${jsonModel.name}.${key.name}: ')
..writeln('\'$jsonValue\',');
});
sb
..writeln('};')
..writeln()
..writeln('const reverse${jsonModel.name}Mapping = {');
jsonModel.fields?.forEach((key) {
final jsonValue = key.value == null || key.value?.isEmpty == null
? key.serializedName
: key.value;
sb
..write(' \'$jsonValue\': ')
..writeln('${jsonModel.name}.${key.name},');
});
sb.writeln('};');
if (jsonModel.generateExtensions) {
sb
..writeln()
..writeln(
'extension ${jsonModel.name}Extension on ${jsonModel.name} {')
..writeln(
' String get stringValue => ${jsonModel.name}Mapping[this]!;')
..writeln('}')
..writeln()
..writeln('extension ${jsonModel.name}StringExtension on String {')
..writeln(
' ${jsonModel.name}? get as${jsonModel.name} => reverse${jsonModel.name}Mapping[this];')
..writeln('}');
}
}
return sb.toString();
}
}