Luna Tech

Tutorials For Dummies.

GraphQL Server

2021-09-15


Reference


1. Resolver

每个 field 都有 resolver,但是我们不需要一个个写,因为 GraphQL Server 会 implement default resolvers。

Query fields are resolved breadth-first.

Not only root fields, but virtually all fields on the types in a GraphQL schema have resolver functions.

Batched Resolving

为了减少重复 fetch 同样的资源,我们需要有个 strategy,在 JS 里面有个 Data Loader Utility,大概的流程就是先把要 fetch 的东西通通 load 进去,然后再统一去 fetch 所有不同的资源。

In JavaScript, the above strategies can be implemented using a utility called DataLoader , and there are similar utilities for other languages.

query resolution process

Effectively, all the GraphQL server has to do is invoke all resolver functions for the fields that are contained in the query and then package up the response according to the query’s shape. Query resolution thus merely becomes a process of orchestrating the invocation of resolver functions!

因为每个 field 都有 resolver function,所以 query resolution 就是 invoke 这些 function 然后整合结果。

Resolver function

每个 resolver function 都有四个 parameter。

parent

上一个 level 的 resolver execution result。

因为 gql 是 nested,所以每个 level 都有 parent。

args

Mutation 接收 variable 的方式。

context


2. Caching

Challenging on server side.


3. Error handling

It returns a dedicated errors object in the server response.

{
  "data": { ... },
  "errors": [ ... ]
}

4. 怎么加新的 feature?

  1. 先改 schema,比如加一个新的 type;
  2. implement resolver to the added fields.

This process is also referred to as schema-driven or schema-first development.


5. Tips

我们可以 create 一个 graphql file,专门来放 typeDef, 参考这个 commit

One convenient thing about the constructor of the GraphQLServer is that typeDefs can be provided either directly as a string (as you previously did) or by referencing a file that contains your schema definition.