net.morimekta.providence.graphql.gql.GQLQuery Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of providence-graphql Show documentation
Show all versions of providence-graphql Show documentation
Providence Core extension for GraphQL.
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 operationMap;
private final Map fragmentMap;
private final boolean defaultOperationAvailable;
public GQLQuery(@Nonnull Map operationMap,
@Nonnull Map 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 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());
}
}
}