generateQueryClassSpec function
Generates a Spec
of a query/mutation class.
Implementation
Spec generateQueryClassSpec(QueryDefinition definition) {
final typeDeclaration = definition.inputs.isEmpty
? '${definition.name.namePrintable}, JsonSerializable'
: '${definition.name.namePrintable}, ${definition.className}Arguments';
final name = '${definition.className}${definition.suffix}';
final constructor = definition.inputs.isEmpty
? Constructor()
: Constructor((b) => b
..optionalParameters.add(Parameter(
(p) => p
..name = 'variables'
..toThis = true
..named = true
..required = true,
)));
final fields = [
Field(
(f) => f
..annotations.add(CodeExpression(Code('override')))
..modifier = FieldModifier.final$
..type = refer('DocumentNode', 'package:gql/ast.dart')
..name = 'document'
..assignment = Code(definition.documentName.constantCase),
),
Field(
(f) => f
..annotations.add(CodeExpression(Code('override')))
..modifier = FieldModifier.final$
..type = refer('String')
..name = 'operationName'
..assignment = Code(definition.documentOperationName.constantCase),
),
];
if (definition.inputs.isNotEmpty) {
fields.add(Field(
(f) => f
..annotations.add(CodeExpression(Code('override')))
..modifier = FieldModifier.final$
..type = refer('${definition.className}Arguments')
..name = 'variables',
));
}
return Class(
(b) => b
..name = name
..extend = refer('GraphQLQuery<$typeDeclaration>')
..constructors.add(constructor)
..fields.addAll(fields)
..methods.add(_propsMethod([
'document',
'operationName${definition.inputs.isNotEmpty ? ', variables' : ''}'
]))
..methods.add(Method(
(m) => m
..annotations.add(CodeExpression(Code('override')))
..returns = refer(definition.name.namePrintable)
..name = 'parse'
..requiredParameters.add(Parameter(
(p) => p
..type = refer('Map<String, dynamic>')
..name = 'json',
))
..lambda = true
..body = Code('${definition.name.namePrintable}.fromJson(json)'),
)),
);
}