V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
FingerLiu
V2EX  ›  程序员

json to graphql schema: json2graphql

  •  
  •   FingerLiu · 2019-02-02 11:42:55 +08:00 · 1443 次点击
    这是一个创建于 1903 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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

    • [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

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

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2812 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 11:41 · PVG 19:41 · LAX 04:41 · JFK 07:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.