graphQL-java实战(二)

数据获取类

复制代码
public class GraphQLDataFetchers {

    private static List<Map<String, String>> books = Arrays.asList(
            ImmutableMap.of("id", "book-1",
                    "name", "Harry Potter and the Philosopher's Stone",
                    "pageCount", "223",
                    "authorId", "author-1"),
            ImmutableMap.of("id", "book-2",
                    "name", "Moby Dick",
                    "pageCount", "635",
                    "authorId", "author-2"),
            ImmutableMap.of("id", "book-3",
                    "name", "Interview with the vampire",
                    "pageCount", "371",
                    "authorId", "author-3")
    );

    private static List<Map<String, String>> authors = Arrays.asList(
            ImmutableMap.of("id", "author-1",
                    "firstName", "Joanne",
                    "lastName", "Rowling"),
            ImmutableMap.of("id", "author-2",
                    "firstName", "Herman",
                    "lastName", "Melville"),
            ImmutableMap.of("id", "author-3",
                    "firstName", "Anne",
                    "lastName", "Rice")
    );

    public static DataFetcher getBookByIdDataFetcher() {
        return dataFetchingEnvironment -> {
            String bookId = dataFetchingEnvironment.getArgument("id");
            return books
                    .stream()
                    .filter(book -> book.get("id").equals(bookId))
                    .findFirst()
                    .orElse(null);
        };
    }

    public static DataFetcher getAuthorDataFetcher() {
        return dataFetchingEnvironment -> {
            Map<String,String> book = dataFetchingEnvironment.getSource();
            String authorId = book.get("authorId");
            return authors
                    .stream()
                    .filter(author -> author.get("id").equals(authorId))
                    .findFirst()
                    .orElse(null);
        };
    }
}
复制代码

schema文件book.graphqls

复制代码
type Query {
    bookById(id: ID): Book
}

type Book {
    id: ID
    name: String
    pageCount: Int
    author: Author
}

type Author {
    id: ID
    firstName: String
    lastName: String
}
复制代码

query文件book.query

复制代码
{
    bookById(id: "book-2"){
        id
        name
        pageCount
        author {
            firstName
            lastName
        }
    }
}
复制代码

入口类

复制代码
public class GraphQLSDLDemoV3 {

    public static void main(String[] args) throws IOException {
        String schemaFileName = "book.graphqls";
        String queryFileName = "book.query";
        String query = getFileContent(queryFileName);
        String schema = getFileContent(schemaFileName);
        System.out.println(schema);

        //typeName=class,fieldName=field|method
        List<TypeRuntimeWiring.Builder> list = Lists.newArrayList();
        list.add(newTypeWiring("Query")
                .dataFetcher("bookById", GraphQLDataFetchers.getBookByIdDataFetcher()));
        list.add(newTypeWiring("Book")
                .dataFetcher("author", GraphQLDataFetchers.getAuthorDataFetcher()));
        RuntimeWiring wiring = buildWiring(list);


        GraphQL graphQL = buildGraphQL(schema, wiring);


        ExecutionResult result = graphQL.execute(query);

        System.out.println("query: " + query);
        System.out.println(result.toSpecification());
        String s = JSON.toJSONString(result.toSpecification());
        System.out.println(s);
    }

    public static GraphQL buildGraphQL(String schema, RuntimeWiring wiring) {
        TypeDefinitionRegistry typeDefinitionRegistry = new SchemaParser().parse(schema);
        GraphQLSchema graphQLSchema = new SchemaGenerator().makeExecutableSchema(typeDefinitionRegistry, wiring);

        return GraphQL.newGraphQL(graphQLSchema).build();
    }

    public static RuntimeWiring buildWiring(List<TypeRuntimeWiring.Builder> builders) {
        RuntimeWiring.Builder builder = RuntimeWiring.newRuntimeWiring();
        for (TypeRuntimeWiring.Builder builder1 : builders) {
            builder.type(builder1);
        }
        return builder.build();
    }


    public static String getFileContent(String fileName) throws IOException {
        URL url = Resources.getResource(fileName);
        String sdl = Resources.toString(url, Charsets.UTF_8);
        return sdl;
    }
}
复制代码

执行输出:

复制代码
query: {
    bookById(id: "book-2"){
        id
        name
        pageCount
        author {
            firstName
            lastName
        }
    }
}
{data={bookById={id=book-2, name=Moby Dick, pageCount=635, author={firstName=Herman, lastName=Melville}}}}
{"data":{"bookById":{"id":"book-2","name":"Moby Dick","pageCount":635,"author":{"firstName":"Herman","lastName":"Melville"}}}}
复制代码

 

posted @   Mars.wang  阅读(397)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
历史上的今天:
2020-07-20 python借助zookeeper实现分布式服务(一)
点击右上角即可分享
微信分享提示