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: inspectgenerate a graphql schema based on json help, hShows a list of commands or help for one command GLOBAL OPTIONS: --verbose, -vshow logs --input value, -i valuethe json filename --output value, -o valuethe target filename to store generated schema --help, -hshow help
Example
go run main.go -i example.json
Live Demo
https://luojilab.github.io/js...