All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.morimekta.providence.graphql.gql.GQLQuery Maven / Gradle / Ivy

There is a newer version: 2.7.0
Show newest version
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());
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy