platform/graphql_schema/lib/src/union.dart

61 lines
1.5 KiB
Dart
Raw Normal View History

2018-08-04 00:22:50 +00:00
part of graphql_schema.src.schema;
2018-08-04 00:57:38 +00:00
class GraphQLUnionType
extends GraphQLType<Map<String, dynamic>, Map<String, dynamic>>
with _NonNullableMixin<Map<String, dynamic>, Map<String, dynamic>> {
final String name;
final List<GraphQLObjectType> possibleTypes = [];
GraphQLUnionType(
this.name,
Iterable<GraphQLObjectType> possibleTypes,
) {
assert(possibleTypes.isNotEmpty,
2018-08-04 00:57:38 +00:00
'A Union type must define one or more member types.');
this.possibleTypes.addAll(possibleTypes.toSet());
2018-08-04 00:22:50 +00:00
}
@override
2018-08-04 00:57:38 +00:00
String get description => possibleTypes.map((t) => t.name).join(' | ');
@override
2018-08-04 00:57:38 +00:00
Map<String, dynamic> serialize(Map<String, dynamic> value) {
for (var type in possibleTypes) {
try {
return type.serialize(value);
} catch (_) {}
}
throw new ArgumentError();
}
@override
2018-08-04 00:57:38 +00:00
Map<String, dynamic> deserialize(Map<String, dynamic> serialized) {
for (var type in possibleTypes) {
try {
return type.deserialize(serialized);
} catch (_) {}
}
throw new ArgumentError();
}
@override
2018-08-04 00:57:38 +00:00
ValidationResult<Map<String, dynamic>> validate(
String key, Map<String, dynamic> input) {
List<String> errors = [];
for (var type in possibleTypes) {
var result = type.validate(key, input);
if (result.successful) {
return result;
} else {
errors.addAll(result.errors);
}
}
2018-08-04 00:57:38 +00:00
return new ValidationResult<Map<String, dynamic>>._failure(errors);
}
}