GraphQL

是什么?

GraphQL is an open-source data query and manipulation language for APIs, and a runtime for fulfilling queries with existing data.(wiki)

a query language and execution engine originally created at Facebook in 2012 for describing the capabilities and requirements of data models for client‐server applications. (specification for GraphQL)

github 的api的v4的接口就是用GraphQL来提供的,最后一个L,是language的意思,也就是说是有一定的规范的,最典型的是有自己type,有自己的schema。这点与restful不同,restful只是一种架构风格,从约束强度上看,GraphQL的约束更强。其实更强的约束也代表更少的歧义,更多的可复用。

与restful场景一样,在client-service的应用场景中.

Github中对GraphQL的描述:

A specification. The spec determines the validity of the schema on the API server. The schema determines the validity of client calls.

是一个规范,GraphQL,不长不短.这一点上,比restful的规范严格很多,有些像IDL (Interface Description Language),有自己的类型,而且客户端知道了这规范就能自己去调用. 与restful的Hypermedia as the engine of application state (HATEOAS)相比,更加直接.

这个规范,不一定非要server端给出,而是一种双方的契约.相当于以前的api文档的契约.

Strongly typed. The schema defines an API’s type system and all object relationships.

强类型,这类型不仅仅是字段的type,而且还有对象之间的关系.

Introspective. A client can query the schema for details about the schema.

自省.自解释?一套schema描述,然后客户端就能调用了,代替部分api文档功能.

Hierarchical. The shape of a GraphQL call mirrors the shape of the JSON data it returns. Nested fields let you query for and receive only the data you specify in a single round trip.

有层次的.使用json来标识多层次性.这与restful不一样,restful更推荐不使用多层嵌套,最好是一层key-value,保持对象的简单理解.其实GraphQL并不是鼓励多层嵌套,而是返回的时候,相关的需要的对象一起返回,一次返回.对于app应用更友好,省流量.

An application layer. GraphQL is not a storage model or a database query language. The graph refers to graph structures defined in the schema, where nodes define objects and edges define relationships between objects. The API traverses and returns application data based on the schema definitions, independent of how the data is stored.

不是SQL,不是存储模型.Graph指的是schema中定义的node的关系.

个人感觉,这GraphQL会反向推进开发人员对于领域的抽象,更像DDD,在开始定义schema的过程,其实更是对领域的抽象,划分的过程.node定义好,关系定义好,然后前端和后端就可以大规模的进行开发,而不是后端定义好两个api给前端,前端做完,等着,后端在定义好几个api在给前端.

这样开始把模型定下后,一般的需求更改,基本不需要后端在修改了,模型的能暴露的都在开始描述清楚了.

Table of Contents