I re-write from Spring boot Rest API to GraphQL
I have Rest Controller generic, common for all controller
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);
}
}
And controllers extend generic controller with generic type is 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 schema
type CustomerEntity {
id: ID!
name: String!
email: String!
}
type ProductEndity {
id: ID!
name: String!
price: Int!
}
type Query {
findAllCustomer: [CustomerEntity]
findAllProduct: [ProductEndity]
}
with this design, no need write code CRUD method in CustomerController/ProductController, but still using CRUD method (findById, findAll, create,...) from generic for CustomerEntity and ProductEntity
With RestAPI, I using 1 method name (findAll) for 2 path /Customer & /Product
http://localhost:7888/Customer/findAll
http://localhost:7888/Product/findAll
But, with GraphQL, I must using 2 method findAllCustomer & findAllProduct
query {
findAllCustomer{
id name email
}
}
query {
findAllProduct{
id name price
}
}
Question: How can I just use 1 method name (findAll) for both Customer and Product, No need to write separate methods for each controller, similar RestAPI
Just like that (I think so:) )
query {
Customer{
findAll{
id name email
}
}
}
query {
Product{
findAll{
id name price
}
}
}
Thanks all!
In GraphQL you can perform multiple queries in a single request. For example:
query giveMeAllTheThings {
allCustomers {
id
name
email
}
allProducts {
id
name
price
}
}
This assumes the following query definitions:
type Query {
allCustomers: [Customer]
allProducts: [Product]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.