GraphQL(六) 联合类型

UnionType

联合类型和接口十分相似,但是它并不指定类型之间的任何共同字段。

Java 方式

package com.tangbaobao.graphql.service;

import com.tangbaobao.graphql.domain.Dog4Interface;
import com.tangbaobao.graphql.domain.Fish4Interface;
import com.tangbaobao.graphql.domain.IAnimal;
import graphql.GraphQL;
import graphql.schema.GraphQLList;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLSchema;
import graphql.schema.GraphQLUnionType;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

import static graphql.Scalars.GraphQLInt;
import static graphql.Scalars.GraphQLString;
import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;
import static graphql.schema.GraphQLObjectType.newObject;
import static graphql.schema.GraphQLUnionType.newUnionType;

/**
 * @author tangxuejun
 * @version 2020/4/4 12:26 上午
 */
@Component
public class UnionTypeTest {
    private GraphQL graphQL;

    private GraphQLObjectType dogType = newObject()//定义Dog类型
            .name("Dog4Interface")
            .field(newFieldDefinition().name("name").type(GraphQLString))
            .field(newFieldDefinition().name("legs").type(GraphQLInt))
            .build();


    private GraphQLObjectType fishType = newObject()//定义Fish类型
            .name("Fish4Interface")
            .field(newFieldDefinition().name("name").type(GraphQLString))
            .field(newFieldDefinition().name("tailColor").type(GraphQLString))
            .build();

    private GraphQLUnionType animalUnion = newUnionType()
            .name("IAnimal")
            .possibleType(dogType)
            .possibleType(fishType)
            .description("动物接口")
            .typeResolver(env -> {
                if (env.getObject() instanceof Dog4Interface) {
                    return dogType;
                }
                if (env.getObject() instanceof Fish4Interface) {
                    return fishType;
                }
                return null;
            })
            .build();

    @PostConstruct
    public void init() {
        //服务端实例数据
        Dog4Interface dog = new Dog4Interface();
        dog.setName("dog");
        dog.setLegs(4);
        Fish4Interface fish = new Fish4Interface();
        fish.setName("fish");
        fish.setTailColor("red");

        IAnimal[] animals = {dog, fish};

        //定义暴露给客户端的查询API
        GraphQLObjectType queryType = newObject().name("Query")
                .field(newFieldDefinition()
                        .type(GraphQLList.list(animalUnion))
                        .name("animals")
                        .dataFetcher(environment -> animals)
                ).build();


        //创建Schema
        GraphQLSchema schema = GraphQLSchema.newSchema()
                .query(queryType)
                .build();

        graphQL = GraphQL.newGraphQL(schema).build();
    }

    @Bean
    public GraphQL graphQL() {
        return graphQL;
    }
}

SDL方式

SDL文件

schema {
    query: Query
}

type Query{
    # 查询所有动物
    animals:[IAnimal]
}
union IAnimal = Dog4Interface|Fish4Interface

type Dog4Interface{
    name:String!
    #有几条腿
    legs:Int
}

type Fish4Interface{
    name:String!
    # 尾巴的颜色
    tailColor:String
}

Java Schema

package com.tangbaobao.graphql.service;

import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import com.tangbaobao.graphql.domain.Dog4Interface;
import com.tangbaobao.graphql.domain.Fish4Interface;
import com.tangbaobao.graphql.domain.IAnimal;
import graphql.GraphQL;
import graphql.schema.DataFetcher;
import graphql.schema.GraphQLSchema;
import graphql.schema.idl.*;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * @author tangxuejun
 * @version 2020/4/4 12:26 上午
 */
@Component
public class UnionTypeTestWithSDL {
    private GraphQL graphQL;
    
    @PostConstruct
    public void init() throws IOException {
        URL url = Resources.getResource("union.graphqls");
        String sdl = Resources.toString(url, Charsets.UTF_8);
        GraphQLSchema graphQLSchema = this.getGraphQLSchema(sdl);
        graphQL = GraphQL.newGraphQL(graphQLSchema).build();
    }

    private GraphQLSchema getGraphQLSchema(String sdl) {
        TypeDefinitionRegistry typeDefinitionRegistry = new SchemaParser().parse(sdl);
        RuntimeWiring runTimeWiring = this.getRunTimeWiring();
        SchemaGenerator schemaGenerator = new SchemaGenerator();
        return schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runTimeWiring);
    }


    //创建TypeRunWring
    private RuntimeWiring getRunTimeWiring() {
        return RuntimeWiring.newRuntimeWiring()
                .type("Query", builder ->
                        builder.dataFetcher("animals", this.getAnimalDataFetcher()))
                .type(TypeRuntimeWiring.newTypeWiring("IAnimal")
                .typeResolver(env -> {
                    if (env.getObject() instanceof Dog4Interface) {
                        return env.getSchema().getObjectType("Dog4Interface");
                    }
                    if (env.getObject() instanceof Fish4Interface) {
                        return env.getSchema().getObjectType("Fish4Interface");
                    }
                    return null;
                }))
                .build();
    }

    private DataFetcher<List<IAnimal>> getAnimalDataFetcher() {
        Dog4Interface dog = new Dog4Interface();
        dog.setName("dog");
        dog.setLegs(4);
        Fish4Interface fish = new Fish4Interface();
        fish.setName("fish");
        fish.setTailColor("red");
        IAnimal[] animals = {dog, fish};
        return environment -> Arrays.asList(animals);
    }

    @Bean
    public GraphQL graphQL() {
        return graphQL;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值