springboot整合graphql

GraphQL是比REST更高效、强大和灵活的新一代API标准。详细的可以看官网GraphQL

下面介绍一个Spring boot整合graphql简单的例子。

  • 项目准备:相关依赖的引入:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    <dependencies>
    <!--web -->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--lombok -->
    <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
    </dependency>
    <!--graphql -->
    <dependency>
    <groupId>com.graphql-java-kickstart</groupId>
    <artifactId>graphql-spring-boot-starter</artifactId>
    <version>11.0.0</version>
    </dependency>
    <!--playground -->
    <dependency>
    <groupId>com.graphql-java-kickstart</groupId>
    <artifactId>playground-spring-boot-starter</artifactId>
    <version>11.0.0</version>
    </dependency>
    </dependencies>

Query

  • 定义schema,分别为:

    query.graphqls

    1
    2
    3
    type Query{
    billingAccount(id: ID): BillingAccount
    }

    billingAccount.graphqls

    1
    2
    3
    4
    5
    type BillingAccount {
    id: ID!
    name: String!
    currency: Currency
    }

    currency.graphqls

    1
    2
    3
    4
    enum Currency{
    RMB,
    USD
    }
  • 定义基础要操作的模型

    1
    2
    3
    4
    5
    6
    7
    @Builder
    @Value
    public class BillingAccount {
    UUID id;
    String name;
    Currency currency;
    }
    1
    2
    3
    public enum Currency {
    RMB, USD
    }
  • 定义resolver

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @Slf4j
    @Component
    public class BillingAccountResolver implements GraphQLQueryResolver {
    public BillingAccount billingAccount(UUID id){
    log.info("receive billingAccount id is: "+ id);
    return BillingAccount.builder()
    .id(id)
    .currency(Currency.RMB)
    .name("张三")
    .build();
    }
    }
  • 效果图

img

mutation

  • 定义schema
1
2
3
type Mutation{
createBillingAccount(input: CreateBillingAccountInput): BillingAccount
}
  • 定义input
1
2
3
input CreateBillingAccountInput{
name: String
}
  • 定义input 对应的model
1
2
3
4
@Data
public class CreateBillingAccountInput {
String name;
}
  • 定义mutationResolver
1
2
3
4
5
6
7
8
9
10
11
12
@Component
public class BillingAccountMutation implements GraphQLMutationResolver {

public BillingAccount createBillingAccount(CreateBillingAccountInput input){

return BillingAccount.builder()
.id(UUID.randomUUID())
.currency(Currency.RMB)
.name(input.getName())
.build();
}
}

效果图

!mutation


springboot整合graphql
http://example.com/springboot整合graphql/
作者
Panyurou
发布于
2021年10月6日
许可协议