toFreezedTupleClass function
Implementation
Spec toFreezedTupleClass(
String className,
ts.ObjectType obj,
GenOption option,
) {
final requiredParameters = <Parameter>[];
final fromJson = StringBuffer();
final toJson = StringBuffer();
final toJsonFields = StringBuffer();
obj.children.forEachIndexed((index, e) {
final child = e.child;
final fieldName = 'item${index + 1}';
final isOpt = child is ts.OptType;
var dartType = child.dartType();
if (isOpt && !dartType.endsWith('?')) {
dartType += '?';
}
final type = Reference(dartType);
requiredParameters.add(
Parameter(
(b) => b
..type = type
..docs = ListBuilder(
['/// [$fieldName] defined in Candid: `${child.did}`'],
)
..name = fieldName,
),
);
var deserialize = child.deserialize();
if (deserialize != null) {
deserialize = deserialize.replaceAll(ts.IDLType.ph, 'tuple[$index]');
} else {
deserialize = 'tuple[$index]';
}
fromJson.writeln('$deserialize,');
final ser = child.serialize();
final arg =
ser == null ? fieldName : ser.replaceAll(ts.IDLType.ph, fieldName);
toJson.writeln('$arg,');
toJsonFields.writeln('final $fieldName = this.$fieldName;');
});
return Class(
(b) => b
..name = className
..mixins = ListBuilder([Reference('_\$$className')])
..annotations = ListBuilder([CodeExpression(Code(option.annotation))])
..constructors = ListBuilder([
Constructor(
(b) => b
..name = '_'
..constant = true,
),
Constructor(
(b) => b
..requiredParameters = ListBuilder(requiredParameters)
..redirect = Reference('_$className')
..factory = true
..constant = true,
),
Constructor(
(b) => b
..name = 'fromJson'
..factory = true
..body = Code('return $className($fromJson);')
..requiredParameters = ListBuilder([
Parameter(
(b) => b
..type = const Reference('List<dynamic>')
..name = 'tuple',
),
]),
),
])
..methods = ListBuilder([
Method(
(b) => b
..name = 'toJson'
..body = Code('${toJsonFields}return [$toJson];')
..returns = const Reference('List<dynamic>'),
),
toStringMethod,
])
..docs = ListBuilder(['/// [$className] defined in Candid', obj.doc]),
);
}