我从 Spring boot Rest API 重写为 GraphQL
我有通用的 Rest 控制器,适用于所有控制器
public class GenericController<E, P extends Serializable>{
@Autowired
private GenericService<E, P> genericService;
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Object> findById(@PathVariable P id) {
return new ResponseEntity<>(genericService.findById(id), HttpStatus.OK);
}
@RequestMapping(value = "/findAll", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Object> findAll() {
return new ResponseEntity<>(genericService.findAll(), HttpStatus.OK);
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Object> create(@RequestBody @Valid E e) {
return new ResponseEntity<>(genericService.save(e), HttpStatus.OK);
}
}
控制器扩展通用控制器,通用类型为Entity
@RestController
@RequestMapping("/Customer")
public class CustomerController extends GenericController<CustomerEntity, Long> implements GraphQLQueryResolver{
public List<CustomerEntity> findAllCustomer(){//This method is only for GraphQL
return findAll();
}
}
@RestController
@RequestMapping("/Product")
public class ProductController extends GenericController<ProductEntity, Long> implements GraphQLQueryResolver{
public List<ProductEntity> findAllProduct(){//This method is only for GraphQL
return findAll();
}
}
GraphQL 架构
type CustomerEntity {
id: ID!
name: String!
email: String!
}
type ProductEndity {
id: ID!
name: String!
price: Int!
}
type Query {
findAllCustomer: [CustomerEntity]
findAllProduct: [ProductEndity]
}
通过这种设计,无需在 CustomerController/ProductController 中编写代码 CRUD 方法,但仍然使用 CustomerEntity 和 ProductEntity 的通用 CRUD 方法(findById、findAll、create...)
使用 RestAPI,我使用 1 个方法名称 (findAll) 来表示 2 个路径 /Customer & /Product
http://localhost:7888/Customer/findAll
http://localhost:7888/Product/findAll
但是,使用 GraphQL,我必须使用 2 种方法 findAllCustomer 和 findAllProduct
query {
findAllCustomer{
id name email
}
}
query {
findAllProduct{
id name price
}
}
问题: 我如何为客户和产品使用1个方法名称(findAll),无需为每个控制器编写单独的方法,类似RestAPI
就这样(我也这么认为:))
query {
Customer{
findAll{
id name email
}
}
}
query {
Product{
findAll{
id name price
}
}
}
谢谢大家!
在 GraphQL 中,您可以在单个请求中执行多个查询。例如:
query giveMeAllTheThings {
allCustomers {
id
name
email
}
allProducts {
id
name
price
}
}
这假设以下查询定义:
type Query {
allCustomers: [Customer]
allProducts: [Product]
}