TypeFieldProvider.java

package net.morimekta.providence.graphql.utils;

import net.morimekta.providence.descriptor.PField;
import net.morimekta.providence.descriptor.PMessageDescriptor;
import net.morimekta.providence.graphql.GQLDefinition;
import net.morimekta.providence.graphql.GQLFieldProvider;
import net.morimekta.providence.graphql.gql.GQLField;
import net.morimekta.providence.graphql.introspection.Type;
import net.morimekta.providence.graphql.introspection.TypeKind;
import net.morimekta.util.collect.UnmodifiableList;

import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class TypeFieldProvider extends BaseTypeProvider implements GQLFieldProvider<Type> {
    public TypeFieldProvider(@Nonnull GQLDefinition definition) {
        super(definition);
    }

    @Override
    public PMessageDescriptor<Type> getDescriptor() {
        return Type.kDescriptor;
    }

    @Nonnull
    @Override
    public Collection<PField<Type>> getFields() {
        return UnmodifiableList.listOf(
                Type._Field.INTERFACES,
                Type._Field.POSSIBLE_TYPES);
    }

    @Override
    public List<Type> provide(@Nonnull Type message, @Nonnull PField<Type> field, @Nonnull GQLField selection) {
        if (selection.getField() == Type._Field.POSSIBLE_TYPES) {
            if (message.getKind() == TypeKind.UNION ||
                message.getKind() == TypeKind.INTERFACE) {
                if (message.numPossibleTypes() > 0) {
                    return message.getPossibleTypes()
                                  .stream()
                                  .map(this::resolveType)
                                  .collect(Collectors.toList());
                } else {
                    return UnmodifiableList.listOf();
                }
            }
        }
        if (selection.getField() == Type._Field.INTERFACES) {
            if (message.getKind() == TypeKind.OBJECT) {
                if (message.numInterfaces() > 0) {
                    return message.getInterfaces()
                                  .stream()
                                  .map(this::resolveType)
                                  .collect(Collectors.toList());
                } else {
                    return UnmodifiableList.listOf();
                }
            }
        }
        return null;
    }
}