Graphql Tutorials(Episode 01)

1.前言

最近认识到Graphql,它是一个基于DSL的api。我曾接触过一个pos机刷卡系统,它是基于JSON-DSL语言开发的框架,很有趣。可是后来,没有机会深入研究。直到最近我认识了Graphql,所以想深入学习,打算写一个系列完整的posts,记录一下。

2.什么是Graphql

你就可以理解成操作数据的API。

如果你使用过Restful,那么理解Graphql也会相当容易。在Restful中,我们为了查询数据,有可能进行了多次查询才能得到我们想要的数据;也可能查询了一次,但是里面大部分数据都是我们这次查询中不需要的。为了解决上述的问题,Graphql出现了。

它是Facebook于2012年开发的内部系统,于2015年发布面向大众。

3.例子

我们来看看它的样子,感受一下:

Post Request:(很像JSON,但不是)

{
    orders {
        id
        productsList {
            product {
                name
                price
            }
            quantity
        }
        totalAmount
    }
}

Answer:

{
    "data": {
        "orders": [
            {
                "id": 1,
                "productsList": [
                    {
                        "product": {
                            "name": "orange",
                            "price": 1.5
                        },
                        "quantity": 100
                    }
                ],
                "totalAmount": 150
            }
        ]
    }
}

4.Helloword

我们先看一个最简单的例子,对Graphql整体有个认识。目的是让大家认知它大体的样子,以及GraphQL加载的流程。

 1 public class GettingStarted {
 2 
 3     final static Logger logger = LoggerFactory.getLogger(GettingStarted.class);
 4 
 5     public static void main(String[] args) {
 6         String schema = "type Query{hello: String}";
 7 
 8         SchemaParser schemaParser = new SchemaParser();
 9         TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);
10 
11         RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring()
12             .type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("world")))
13             .build();
14 
15         SchemaGenerator schemaGenerator = new SchemaGenerator();
16         GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
17 
18         GraphQL build = GraphQL.newGraphQL(graphQLSchema).build();
19         ExecutionResult executionResult = build.execute("{hello}");
20 
21         System.out.println(executionResult.getData().toString());
22         // Prints: {hello=world}
23     }
24 
25 }

我们可以看到上面的例子中,第6行,我们定义了schema,如果在项目中,应该是一个schema文件。读取这个schema文件后,进行解析得到TypeDefinitionRegistry。然后是执行时的绑定,RuntimeWiring,也即是客户端发送一个请求“hello”,服务端根据这个请求,应该进行什么样的处理。接下来,用TypeDefinitionRegistry和RuntimeWiring,生成GraphQLSchema,进行生成GraphQL。在第19行中,就是执行请求的部分,最后在21行,将返回结果打印出来。

上面的这段话整理一下,流程如下:

到此为止,我们了解了Graphql的背景,对它有个整体的认识。不要着急,知识一点点学习积累。在下一篇的post中,我会给出更具体的示例。

这篇post代码我放在了Github上:

https://github.com/lihao5257/GraphqlDemo.git     分支是master

参考链接:

https://en.wikipedia.org/wiki/GraphQL

原文地址:https://www.cnblogs.com/lihao007/p/13916821.html