GraphQL入门实战

解决什么问题

根据请求控制返回结果

例如: 一个User对象,有id,name,mobile,email

有些接口只要返回id,name ,有些接口还要要返回 mobile

GraphQL入门实战_第1张图片

适用场景

  • 弱文档管理,公司对文档要求不高
  • 需求复杂变化快
  • 单资源多种访问方式,组件复用
  • 复杂API 还是restful好

开发流程

1.设计领域对象

2.定义GraphQL Schema

3.定义DataFetcher(实现数据访问层组件)

4.完成Data Wiring(GraphQlSourceBuilderCustomizer,旧版本RuntimeWiringBuilderCustomizer)

5.开启graph配置或者自己实现Controller

 spring.graphql.schema.printer.enabled=true

 spring.graphql.path=/wenl/query

GraphQL Server实例

前提

spring boot 2.7+,JDK1.8,maven 3.5+

maven pom如下:

	
		org.springframework.boot
		spring-boot-starter-parent
		2.7.13-SNAPSHOT
		 
	

	
		1.8
	
	
		
			org.springframework.boot
			spring-boot-starter-graphql
		
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
			org.springframework
			spring-webflux
			test
		
		
			org.springframework.graphql
			spring-graphql-test
			test
		
		
			org.projectlombok
			lombok
			true
		
	
   
		
			
				org.springframework.boot
				spring-boot-maven-plugin
				3.1.0
			
		
	

设计领域对象

@Data
public class Author {

    private Long id;

    private String firstName;

    private String lastName;
}
@Data
@NoArgsConstructor
public class Book {

    private String id;

    private String name;

    private int pageCount;

    private Author author;

    public static List books = Arrays.asList(
            new Book("book-1", "Effective Java", 416, "author-1"),
            new Book("book-2", "Hitchhiker's Guide to the Galaxy", 208, "author-2"),
            new Book("book-3", "Down Under", 436, "author-3")
    );

    public Book(String id, String name, int pageCount, String authorName) {
        this.id = id;
        this.name = name;
        this.pageCount = pageCount;
        Author author = new Author();
        author.setFirstName(authorName);
        author.setLastName("lastName");
        this.author=author;
    }
}

定义GraphQL Schema

文件位置固定文件名固定,resources/graphql/schema.graphqls

schema {
    query : Query
}

type Query {
    books: [Book]
    bookById(id: String,name: String ): Book
}

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

type Author {
    id: ID
    firstName: String
    lastName: String
}

schema 是固定写法

type Query  内部是对应的查询方法。

books: [Book] 表示方法名称为books(client需要配置) ,返回的是list


bookById(id: String,name: String ): Book   这里返回单个Book,id,name是参数

其他的type 是返回值的类。

定义DataFetcher(实现数据访问层组件)

@Component
public class BookDataFetcher implements DataFetcher {

    @Override
    public Book get(DataFetchingEnvironment dataFetchingEnvironment) throws Exception {
        String id = (String) dataFetchingEnvironment.getArguments().get("id");
        String name = (String) dataFetchingEnvironment.getArguments().get("name");
        return Book.books.stream().filter(book -> book.getId().equals(id)&&book.getName().equals(name)).findFirst().orElse(null);
    }
    
}
@Component
public class BooksDataFetcher implements DataFetcher> {

    @Override
    public List get(DataFetchingEnvironment dataFetchingEnvironment) throws Exception {
        return Book.books;
    }
    
}

完成Data Wiring(GraphQlSourceBuilderCustomizer,旧版本RuntimeWiringBuilderCustomizer)

@Component
public class CustomerStaffDataWiring implements GraphQlSourceBuilderCustomizer {
    @Autowired
    private BooksDataFetcher booksDataFetcher;
    @Autowired
    private BookDataFetcher bookDataFetcher;
    
    @Override
    public void customize(GraphQlSource.SchemaResourceBuilder builder) {
        builder.configureRuntimeWiring(new RuntimeWiringConfigurer() {
            @Override
            public void configure(RuntimeWiring.Builder builder) {
                builder.type("Query", typeWiring -> typeWiring
                                .dataFetcher("books", booksDataFetcher)
                        .dataFetcher("bookById",bookDataFetcher)
                );
            }
        });
    }
}

开启graph配置或者自己实现Controller

 spring.graphql.schema.printer.enabled=true

 spring.graphql.path=/wenl/query

自实现Controller

@RestController
public class BookController {
    private GraphQL graphQL;

    @Autowired
    public BookController(GraphQlSource graphQlSource) {
        graphQL = graphQlSource.graphQl();
    }
    @Data
    public static class GraphQLInput{
        String query;
        Map variables;
    }
    @PostMapping(value = "/wenl/query")
    public ResponseEntity query(@RequestBody GraphQLInput graphQLInput) {
        ExecutionInput.Builder executionInputBuilder = new ExecutionInput.Builder();
        executionInputBuilder.query(graphQLInput.getQuery());
        executionInputBuilder.variables(graphQLInput.getVariables());
        ExecutionResult result = graphQL.execute(executionInputBuilder);
        return ResponseEntity.ok(result.getData());
    }
} 
  

GraphQL Client 调用方式

就是简单的POST 调用json方式,下面就使用Apifox 说明

GraphQL入门实战_第2张图片

返回值如下:

GraphQL入门实战_第3张图片

调用JSON说明

{
    "query":"query books($id:String,$name:String){ bookById(id:$id,name:$name){ id name pageCount author { firstName  }}}",
    "variables":{
        "id":"book-1",
        "name":"Effective Java"
    }
}

$id,$name 表示参数

query,variables与GraphQLInput 字段一一对应。

你可能感兴趣的:(graphql,java,spring,boot)