GraphQL入门实战

2023-10-16 15:12:54 浏览数 (2)

解决什么问题

根据请求控制返回结果

例如: 一个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如下:

代码语言:javascript复制
	<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>

设计领域对象

代码语言:javascript复制
@Data
public class Author {

    private Long id;

    private String firstName;

    private String lastName;
}
代码语言:javascript复制
@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

代码语言:javascript复制
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(实现数据访问层组件)

代码语言:javascript复制
@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);
    }
    
}
代码语言:javascript复制
@Component
public class BooksDataFetcher implements DataFetcher<List<Book>> {

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

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

代码语言:javascript复制
@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

代码语言:javascript复制
@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 人点赞