y0ngb1n

Aben Blog

欢迎来到我的技术小黑屋ヾ(◍°∇°◍)ノ゙
github

GraphQL 與 Spring Boot 的初體驗

專案已托管於 GitHub:y0ngb1n/spring-boot-samples,歡迎 Star, Fork 😘


GraphQL 既是一種用於 API 的查詢語言也是一個滿足你數據查詢的運行時。 GraphQL 對你的 API 中的數據提供了一套易於理解的完整描述,使得客戶端能夠準確地獲得它需要的數據,而且沒有任何冗餘,也讓 API 更容易地隨著時間推移而演進,還能用於構建強大的開發者工具。

定義 Schema#

# src/main/resources/schema.graphql
schema {
  query: Query
}

type Query {
  allBooks: [Book]
  book(id: String): Book
}

type Book {
  isbn: String
  title: String
  publisher: String
  authors: [String]
  publishedDate: String
}

加載並解析上面定義的 Schema#

@Service
public class GraphQLService {

  @Value("classpath:schema.graphql")
  private Resource resource;

  @Getter
  private GraphQL graphQL;
  @Autowired
  private AllBooksDataFetcher allBooksDataFetcher;
  @Autowired
  private BookDataFetcher bookDataFetcher;

  @PostConstruct
  private void loadSchema() throws IOException {
    // 獲取本地定義的 Schema 文件
    File schemaFile = resource.getFile();
    // 解析 Schema 文件
    TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(schemaFile);
    RuntimeWiring wiring = buildRuntimeWiring();
    GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(typeRegistry, wiring);
    graphQL = GraphQL.newGraphQL(schema).build();
  }

  private RuntimeWiring buildRuntimeWiring() {
    return RuntimeWiring.newRuntimeWiring()
      .type("Query", typeWiring -> typeWiring
        .dataFetcher("allBooks", allBooksDataFetcher)
        .dataFetcher("book", bookDataFetcher)
      ).build();
  }
}

提供 DataFetcher#

相當於提供 Schema 中的 Query 實現:

type Query {
  allBooks: [Book]
  book(id: String): Book
}

AllBooksDataFetcher 對應實現 allBooks: [Book]

@Component
public class AllBooksDataFetcher implements DataFetcher<List<Book>> {

  @Autowired
  private BookRepository bookRepository;

  @Override
  public List<Book> get(DataFetchingEnvironment dataFetchingEnvironment) {
    return bookRepository.findAll();
  }
}

BookDataFetcher 對應實現 book(id: String): Book

@Component
public class BookDataFetcher implements DataFetcher<Book> {

  @Autowired
  private BookRepository bookRepository;

  @Override
  public Book get(DataFetchingEnvironment dataFetchingEnvironment) {
    String isn = dataFetchingEnvironment.getArgument("id");
    return bookRepository.findById(isn).orElse(null);
  }
}

提供 GraphQL API#

@RestController
@RequestMapping(path = "/v1/books")
public class BookController {

  @Autowired
  private GraphQLService graphQLService;

  @PostMapping
  public ResponseEntity<Object> getAllBooks(@RequestBody String query) {
    ExecutionResult execute = graphQLService.getGraphQL().execute(query);
    return new ResponseEntity<>(execute, HttpStatus.OK);
  }
}

啟動並測試#

$ mvn install
...
[INFO] BUILD SUCCESS
...
$ mvn spring-boot:run
...
2019-08-24 19:35:11.700  INFO 14464 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-08-24 19:35:11.702  INFO 14464 --- [           main] i.g.y.s.graphql.GraphQLApplication       : Started GraphQLApplication in 16.808 seconds (JVM running for 25.601)

查詢部分字段

$ curl -X POST \
  http://127.0.0.1:8080/v1/books \
  -H 'Content-Type: text/plain' \
  -d '{
    allBooks {
      isbn
      title
  }
}' | jq
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   579    0   524  100    55  34933   3666 --:--:-- --:--:-- --:--:-- 38600
{
  "errors": [],
  "data": {
    "allBooks": [
      {
        "isbn": "9787111213826",
        "title": "Java 編程思想(第4版)"
      },
      ...
    ]
  },
  "extensions": null,
  "dataPresent": true
}
$ curl -X POST \
  http://127.0.0.1:8080/v1/books \
  -H 'Content-Type: text/plain' \
  -d '{
    book(id: "9787121362132") {
      title
  }
}' | jq
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   210    0   159  100    51   1691    542 --:--:-- --:--:-- --:--:--  2234
{
  "errors": [],
  "data": {
    "book": {
      "title": "高可用可伸縮微服務架構:基於 Dubbo、Spring Cloud 和 Service Mesh"
    }
  },
  "extensions": null,
  "dataPresent": true
}

查詢全部字段

$ curl -X POST \
  http://127.0.0.1:8080/v1/books \
  -H 'Content-Type: text/plain' \
  -d '{
    allBooks {
      isbn
      title
      authors
      publisher
      publishedDate
  }
}' | jq
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  1139    0  1044  100    95    750     68  0:00:01  0:00:01 --:--:--   818
{
  "errors": [],
  "data": {
    "allBooks": [
      {
        "isbn": "9787111213826",
        "title": "Java 編程思想(第4版)",
        "authors": [
          "Bruce Eckel"
        ],
        "publisher": "機械工業出版社",
        "publishedDate": "2007-06-01"
      },
      ...
    ]
  },
  "extensions": null,
  "dataPresent": true
}
$ curl -X POST \
  http://127.0.0.1:8080/v1/books \
  -H 'Content-Type: text/plain' \
  -d '{
    book(id: "9787121362132") {
      title
      authors
      publisher
      publishedDate
  }
}' | jq
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   421    0   320  100   101   312k    98k --:--:-- --:--:-- --:--:--  411k
{
  "errors": [],
  "data": {
    "book": {
      "title": "高可用可伸縮微服務架構:基於 Dubbo、Spring Cloud 和 Service Mesh",
      "authors": [
        "程超",
        "梁桂釗",
        "秦金衛",
        "方志斌",
        "張逸",
        "杜琪",
        "殷琦",
        "肖冠宇"
      ],
      "publisher": "電子工業出版社",
      "publishedDate": "2019-05-01"
    }
  },
  "extensions": null,
  "dataPresent": true
}

查詢多個數據

$ curl -X POST \
  http://127.0.0.1:8080/v1/books \
  -H 'Content-Type: text/plain' \
  -d '{
    allBooks {
      isbn
      title
    }
    book(id: "9787121362132") {
      title
      authors
      publisher
      publishedDate
  }
}' | jq
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   930    0   785  100   145   3866    714 --:--:-- --:--:-- --:--:--  4581
{
  "errors": [],
  "data": {
    "allBooks": [
      {
        "isbn": "9787111213826",
        "title": "Java 編程思想(第4版)"
      },
      {
        "isbn": "9787111421900",
        "title": "深入理解 Java 虛擬機:JVM 高級特性與最佳實踐(第2版)"
      },
      {
        "isbn": "9787115221704",
        "title": "重構 改善既有代碼的設計(第2版)"
      },
      {
        "isbn": "9787121362132",
        "title": "高可用可伸縮微服務架構:基於 Dubbo、Spring Cloud 和 Service Mesh"
      },
      {
        "isbn": "9787302392644",
        "title": "人月神話(40周年中文紀念版)"
      }
    ],
    "book": {
      "title": "高可用可伸縮微服務架構:基於 Dubbo、Spring Cloud 和 Service Mesh",
      "authors": [
        "程超",
        "梁桂釗",
        "秦金衛",
        "方志斌",
        "張逸",
        "杜琪",
        "殷琦",
        "肖冠宇"
      ],
      "publisher": "電子工業出版社",
      "publishedDate": "2019-05-01"
    }
  },
  "extensions": null,
  "dataPresent": true
}

綜上可見,API 不變只改動了查詢的內容,就會自動響應不同的結果。


參考鏈接#

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。