0%

springBoot集成graphql

文章字数:390,阅读全文大约需要1分钟

graphql是一个结构化查询语言,对应的传统方式是rest api

我的理解

  1. rest api一样,graphql主要是为了满足前后端交互需求而产生的一种规范。

  2. 不同的是rest api在创建时就指定了接收的参数以及返回的数据格式,而graphql则可以根据前端使用的不同的传入参数返回之前可能需要好多个rest api才能返回的数据。

rest api获取信息

1
2
# 获取id为1的人员信息
GET /person/1

graphql

1
2
3
4
5
6
# 获取id为1的人员的firstName
{
person(id:1){
firstName
}
}

graphql能够指定信息的输出,以及输出格式。
比如后端有学生,班级两部分信息。

  • rest api获取信息只能根据前端需求,传入能够定位到对象的信息(如id)然后再放回指定的信息格式。仅需要学生名字和需要所有信息的接口需要分开写。
  • graphql则只用把通过id获取对象的方法给graphql框架,前端通过graphql查询语言就能够在指定的范围内查询数据并且指定输出的格式。

搭建环境

  1. 基于 spring-boot 2.0

    1
    2
    3
    4
    5
    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
    </parent>
  2. 引入依赖

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java-tools</artifactId>
<version>4.3.0</version>
</dependency>

实现

  1. 定义服务入口

即有哪些内容可以操作

resource/graphql/root.graphqls

Query查询入口
Mutation修改入口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
type Query {
findAllAuthors: [Author]!
countAuthors: Long!
findOneAuthor(id: Long!): Author

findAllBooks: [Book]!
countBooks: Long!
}
type Mutation {
newAuthor(firstName: String!, lastName: String!) : Author!

newBook(title: String!, isbn: String!, pageCount: Int, authorId: Long!) : Book!
saveBook(input: BookInput!): Book!
deleteBook(id: ID!) : Boolean
updateBookPageCount(pageCount: Int!, id: Long!) : Book!
}

resource/graphql/scheme.graphqls

具体的字段定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
type Author {
id: Long!
createdTime: String
firstName: String
lastName: String
books: [Book]
}
input BookInput {
title: String!
isbn: String!
pageCount: Int
authorId: Long
}
type Book {
id: Long!
title: String!
isbn: String!
pageCount: Int
author: Author
}
  1. 对于定义的入口规则实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Query implements GraphQLQueryResolver {
private AuthorRepository authorRepository;
private BookRepository bookRepository;

public Author findOneAuthor(Long id) {
Optional<Author> opt = authorRepository.findById(id);
return opt.isPresent() ? opt.get() : null;
}
public List<Author> findAllAuthors() {
return authorRepository.findAll();
}
public Long countAuthors() {
return authorRepository.count();
}
public List<Book> findAllBooks() {
return bookRepository.findAll();
}
public Long countBooks() {
return bookRepository.count();
}
}

定义了的Query都要实现