【问题标题】:Graphql parameter passingGraphql 参数传递
【发布时间】:2018-01-09 00:23:17
【问题描述】:

大家好,我刚开始学习如何使用 react/graphql 进行编码,但我很难理解参数传递的工作原理。在下面取自https://github.com/graphql/swapi-graphql 的代码示例中,我不知道resolve 函数何时填充参数“edge”和“conn”。有人可以给我一些见解吗?

export function connectionFromUrls(
  name: string,
  prop: string,
  type: GraphQLOutputType
): GraphQLFieldConfig<*, *> {
  const {connectionType} = connectionDefinitions({
    name,
    nodeType: type,
    resolveNode: edge => getObjectFromUrl(edge.node),
    connectionFields: () => ({
      totalCount: {
        type: GraphQLInt,
        resolve: conn => conn.totalCount,
        description:
`A count of the total number of objects in this connection, ignoring pagination.
This allows a client to fetch the first five objects by passing "5" as the
argument to "first", then fetch the total count so it could display "5 of 83",
for example.`
      },
      [prop]: {
        type: new GraphQLList(type),
        resolve: conn => conn.edges.map(edge => getObjectFromUrl(edge.node)),
        description:
`A list of all of the objects returned in the connection. This is a convenience
field provided for quickly exploring the API; rather than querying for
"{ edges { node } }" when no edge data is needed, this field can be be used
instead. Note that when clients like Relay need to fetch the "cursor" field on
the edge to enable efficient pagination, this shortcut cannot be used, and the
full "{ edges { node } }" version should be used instead.`
      }
    })
  });
  return {
    type: connectionType,
    args: connectionArgs,
    resolve: (obj, args) => {
      const array = obj[prop] || [];
      return {
        ...connectionFromArray(array, args),
        totalCount: array.length
      };
    },
  };
}

【问题讨论】:

    标签: javascript graphql


    【解决方案1】:

    GraphQL 执行器在处理查询时调用resolve 函数。作为开发人员,您不必管理执行者的行为方式;您唯一的目标是指定(在resolve 函数中)该字段返回的内容。关于执行器,您只需要知道它会递归地调用每个字段,直到它到达查询树的所有分支,并将解析的对象向下传递到层次结构。

    当您定义 GraphQL 类型时,您指定它们具有哪些字段,每个字段返回什么类型(例如,User 类型有一个名为 address 的字段可以是 Address 类型等等),以及resolve 将响应查询而执行的函数。 resolve 函数的第一个参数始终是父对象;在这种情况下,conn。 (实际上,edge 被传递给 resolveNode,这是一种处理连接边缘的自定义方法,但这超出了本问题的范围。)

    【讨论】:

      猜你喜欢
      • 2021-12-05
      • 2017-01-02
      • 1970-01-01
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 2023-01-26
      • 2017-02-05
      • 2016-12-12
      相关资源
      最近更新 更多