json to graphql schema: json2graphql

2019-02-02 11:42:55 +08:00
 FingerLiu

json2graphql

json2graphql 是一个根据 json 生成 GraphQL Schema 的工具。 可在 https://luojilab.github.io/json2graphql/ 在线体验其功能。

关于 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/json2graphql/

在从 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/json2graphql/

TODO

文章原文在 https://segmentfault.com/a/1190000018091728

1451 次点击
所在节点    程序员
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/532628

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX