json to graphql schema: json2graphql

json2graphql

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

关于 GraphQL

GraphQL 是一个用于 API 的查询语言,是一个使用基于类型系统来执行查询的服务端运行时(类型系统由你的数据定义)。GraphQL 并无和任何特定数据库或者存储引擎绑定,而是依靠你现有的代码和数据支撑。因为其强类型,返回结果可定制,自带聚合功能等特性,由 facebook 开源后,被 github 等各大厂普遍使用。github

核心概念:golang

更多请参考 https://graphql.cn/web

为何选用 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...json

在从 REST API 迁移到 GraphQL 的过程当中,咱们有不少接口会返回大量字段(几十个),若是彻底手动编写这些 Schema,将是很是痛苦的,咱们开发 json2graphql 的初衷就是解决这个问题,大大缩短开发时间。bash

如下介绍该工具用法。框架

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
相关文章
相关标签/搜索