json to graphql schema: json2graphql

json2graphql

json2graphql 是一個根據 json 生成 GraphQL Schema 的工具。
可在 https://luojilab.github.io/js... 在線體驗其功能。

關於 GraphQL

GraphQL 是一個用於 API 的查詢語言,是一個使用基於類型系統來執行查詢的服務端運行時(類型系統由你的數據定義)。GraphQL 並沒有和任何特定數據庫或者存儲引擎綁定,而是依靠你現有的代碼和數據支撐。由於其強類型,返回結果可定製,自帶聚合功能等特性,由 facebook 開源後,被 github 等各大廠廣泛使用。

核心概念:

更多請參考 https://graphql.cn/

爲什麼選用 GraphQL

相比 REST API, GraphQL 提供了更高的靈活性。接口調用方能夠精確的定義其所需數據,並通知服務方只返回這部分數據,該功能是 REST API 無法提供的。GraphQL 能夠使客戶端只進行一次接口調用,即可獲取多個 REST API 請求返回的數據。這種數據聚合的能力,正是我們所需要的。

json protobuf 與 GraphQL

由於 protobuf 和 GraphQL 都是強類型的,所以可以直接從 protobuf 的 schema 生成 GraphQL Schema,因而纔能有自動聚合 grpc 服務生成 GraphQL 接口的框架 rejoiner。但同樣的方法不適用於 json,因爲標準的 json 並不包含 schema,單純根據 json 文件無法確定知道每個字段的類型(因爲有空值,以及嵌套的情況)。因而目前無法實現類似 rejoiner for json 這樣的全自動框架。
我們雖不能生成最終的 GraphQL Schema,但是基於對 json 的解析和一些約定,我們可以生成一個 GraphQL Schema 的草稿,生成 Schema 的絕大部分內容,並將有疑問的地方標記出來。
json2graphql 就是一個用 golang 實現的 json 生成 schema 的工具。如果你不熟悉 golang,可以使用其在線版本 https://luojilab.github.io/js...

在從 REST API 遷移到 GraphQL 的過程中,我們有很多接口會返回大量字段(幾十個),如果完全手動編寫這些 Schema,將是非常痛苦的,我們開發 json2graphql 的初衷就是解決這個問題,大大縮短開發時間。

以下介紹該工具用法。

Usage

go run main.go -h
NAME:
   inspect - generate a graphql schema based on json

USAGE:
   main [global options] command [command options] [arguments...]

DESCRIPTION:
   inspect json and generate draft schema.graphql

COMMANDS:
     inspect  generate a graphql schema based on json
     help, h  Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --verbose, -v             show logs
   --input value, -i value   the json filename
   --output value, -o value  the target filename to store generated schema
   --help, -h                show help

Example

go run main.go -i example.json

Live Demo

https://luojilab.github.io/js...

TODO

  • [x] build it as a web service that render schema on the fly like json.cn
  • [ ] support to read from multi json files.
  • [ ] get input from http request rather than local file.
  • [ ] integrate with graphql server frameworks like gqlgen and auto generate resolver
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章