GQLFragmentDefinition.java

package net.morimekta.providence.graphql.gql;

import net.morimekta.providence.descriptor.PMessageDescriptor;
import net.morimekta.util.collect.UnmodifiableList;

import javax.annotation.Nonnull;
import javax.annotation.concurrent.Immutable;
import java.util.List;
import java.util.Objects;

/**
 * A fragment definition, as part of the query.
 *
 * {@inheritDoc}
 */
@Immutable
public class GQLFragmentDefinition implements GQLFragment {
    private final PMessageDescriptor<?> descriptor;
    private final List<GQLSelection>    selectionSet;
    private final String                name;

    /**
     * @param name Name of the fragment.
     * @param descriptor Descriptor of type defined in this fragment.
     * @param selectionSet SelectionSet for the fragment.
     */
    public GQLFragmentDefinition(@Nonnull String name,
                                 @Nonnull PMessageDescriptor<?> descriptor,
                                 @Nonnull List<GQLSelection> selectionSet) {
        this.name = name;
        this.descriptor = descriptor;
        this.selectionSet = UnmodifiableList.copyOf(selectionSet);
    }

    @Nonnull
    @Override
    public PMessageDescriptor<?> getTypeCondition() {
        return descriptor;
    }

    @Nonnull
    @Override
    public List<GQLSelection> getSelectionSet() {
        return selectionSet;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("fragment ")
               .append(name)
               .append(" on ")
               .append(descriptor.getName())
               .append(" {");

        boolean first = true;
        for (GQLSelection entry : selectionSet) {
            if (first) {
                first = false;
            } else {
                builder.append(", ");
            }
            builder.append(entry.toString());
        }
        builder.append("}");
        return builder.toString();
    }

    @Override
    public int hashCode() {
        return Objects.hash(getClass(), name, descriptor, selectionSet);
    }
}