GraphQL入门实战

解决什么问题

根据请求控制返回结果

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

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

适用场景

  • 弱文档管理,公司对文档要求不高
  • 需求复杂变化快
  • 单资源多种访问方式,组件复用
  • 复杂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如下:

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.13-SNAPSHOT</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-graphql</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webflux</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.graphql</groupId>
			<artifactId>spring-graphql-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
	</dependencies>
   <build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<version>3.1.0</version>
			</plugin>
		</plugins>
	</build>

设计领域对象

@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<Book> 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<Book> {

    @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<List<Book>> {

    @Override
    public List<Book> 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<String,Object> variables;
    }
    @PostMapping(value = "/wenl/query")
    public ResponseEntity<Object> 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 说明

返回值如下:

调用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 字段一一对应。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值