platform/packages/graphql/graphql_schema/lib/src/union.dart

89 lines
2.6 KiB
Dart
Raw Normal View History

2018-08-04 00:22:50 +00:00
part of graphql_schema.src.schema;
2018-08-05 02:37:00 +00:00
/// A special [GraphQLType] that indicates that an input value may be valid against one or more [possibleTypes].
///
/// All provided types must be [GraphQLObjectType]s.
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>> {
2018-08-05 02:37:00 +00:00
/// The name of this type.
2018-08-04 00:57:38 +00:00
final String name;
2018-08-05 02:37:00 +00:00
/// A list of all types that conform to this union.
2018-08-04 00:57:38 +00:00
final List<GraphQLObjectType> possibleTypes = [];
GraphQLUnionType(
2018-08-04 19:18:53 +00:00
this.name,
Iterable<GraphQLType<Map<String, dynamic>, Map<String, dynamic>>>
possibleTypes) {
assert(possibleTypes.every((t) => t is GraphQLObjectType),
'The member types of a Union type must all be Object base types; Scalar, Interface and Union types must not be member types of a Union. Similarly, wrapping types must not be member types of a Union.');
assert(possibleTypes.isNotEmpty,
2018-08-04 00:57:38 +00:00
'A Union type must define one or more member types.');
2018-08-04 19:18:53 +00:00
for (var t in possibleTypes.toSet()) {
this.possibleTypes.add(t as GraphQLObjectType);
}
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(' | ');
2018-08-04 19:18:53 +00:00
@override
GraphQLType<Map<String, dynamic>, Map<String, dynamic>>
coerceToInputObject() {
return new GraphQLUnionType(
'${name}Input', possibleTypes.map((t) => t.coerceToInputObject()));
}
@override
2018-08-04 00:57:38 +00:00
Map<String, dynamic> serialize(Map<String, dynamic> value) {
for (var type in possibleTypes) {
try {
2018-08-05 01:32:20 +00:00
if (type.validate('@root', value).successful) {
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);
}
2018-08-04 19:18:53 +00:00
@override
bool operator ==(other) =>
other is GraphQLUnionType &&
other.name == name &&
other.description == description &&
const ListEquality<GraphQLObjectType>()
.equals(other.possibleTypes, possibleTypes);
}