GQLQuery.java
package net.morimekta.providence.graphql.gql;
import net.morimekta.util.collect.UnmodifiableMap;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.Immutable;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import static net.morimekta.util.Strings.isNullOrEmpty;
/**
* Representing a complete GQL query, also known as a 'document' in
* the GraphQL spec.
*/
@Immutable
public class GQLQuery {
private final Map<String, GQLOperation> operationMap;
private final Map<String, GQLFragmentDefinition> fragmentMap;
private final boolean defaultOperationAvailable;
public GQLQuery(@Nonnull Map<String, GQLOperation> operationMap,
@Nonnull Map<String, GQLFragmentDefinition> fragmentMap) {
this.operationMap = UnmodifiableMap.copyOf(operationMap);
this.fragmentMap = UnmodifiableMap.copyOf(fragmentMap);
this.defaultOperationAvailable = operationMap.size() == 1;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(operationMap.values().stream().map(Objects::toString).collect(Collectors.joining(" ")));
for (GQLFragmentDefinition fragment : fragmentMap.values()) {
builder.append(" ").append(fragment.toString());
}
return builder.toString();
}
public boolean isDefaultOperationAvailable() {
return defaultOperationAvailable;
}
public Optional<GQLOperation> getOperation(String name) {
if (!isNullOrEmpty(name)) {
return Optional.ofNullable(operationMap.get(name));
} else {
if (operationMap.size() > 1) {
throw new IllegalArgumentException("Multiple operations and no operation name given");
}
// Should never return
return Optional.ofNullable(operationMap.values().iterator().next());
}
}
}