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 @ 2022-07-20 10:24  Mars.wang  阅读(384)  评论(0编辑  收藏  举报