我需要帮助理解中继输出字段,getFatQuery

gpb*_*lio 1 relay graphql graphql-js relayjs

这是中继官方文档中的代码,这是用于 GraphQLAddTodoMutation

const GraphQLAddTodoMutation = mutationWithClientMutationId({
  name: 'AddTodo',
  inputFields: {
    text: { type: new GraphQLNonNull(GraphQLString) },
  },
  outputFields: {
    todoEdge: {
      type: GraphQLTodoEdge,
      resolve: ({localTodoId}) => {
        const todo = getTodo(localTodoId);
        return {
          cursor: cursorForObjectInConnection(getTodos(), todo),
          node: todo,
        };
      },
    },
    viewer: {
      type: GraphQLUser,
      resolve: () => getViewer(),
    },
  },
  mutateAndGetPayload: ({text}) => {
    const localTodoId = addTodo(text);
    return {localTodoId};
  },
});
Run Code Online (Sandbox Code Playgroud)

我认为 mutateAndGetPayload 先执行,然后再执行 outputFields?因为它使用 localTodoId 对象作为参数,所以我看到了从 mutateAndGetPayload 返回的 localTodoId 对象。

这是中继突变的代码。请查看 getFatQuery

export default class AddTodoMutation extends Relay.Mutation {
  static fragments = {
    viewer: () => Relay.QL`
      fragment on User {
        id,
        totalCount,
      }
    `,
  };
  getMutation() {
    return Relay.QL`mutation{addTodo}`;
  }
  getFatQuery() {
    return Relay.QL`
      fragment on AddTodoPayload @relay(pattern: true) {
        todoEdge,
        viewer {
          todos,
          totalCount,
        },
      }
    `;
  }
  getConfigs() {
    return [{
      type: 'RANGE_ADD',
      parentName: 'viewer',
      parentID: this.props.viewer.id,
      connectionName: 'todos',
      edgeName: 'todoEdge',
      rangeBehaviors: ({status}) => {
        if (status === 'completed') {
          return 'ignore';
        } else {
          return 'append';
        }
      },
    }];
  }
  getVariables() {
    return {
      text: this.props.text,
    };
  }
  getOptimisticResponse() {
    return {
      // FIXME: totalCount gets updated optimistically, but this edge does not
      // get added until the server responds
      todoEdge: {
        node: {
          complete: false,
          text: this.props.text,
        },
      },
      viewer: {
        id: this.props.viewer.id,
        totalCount: this.props.viewer.totalCount + 1,
      },
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

我认为 todoEdge 来自 GraphQL 的 outputFields?我在上面看到一个查看器查询,为什么它需要查询查看器?如何创建 getFatQuery?如果有人帮助我更多地了解这一点以及有关 Relay 突变的信息,我将不胜感激。

p0k*_*k8_ 5

mutateAndGetPayload执行然后将有效负载返回到 outputFields

mutationWithClientMutationId

Source-Code

starWarsSchema example


mutationWithClientMutationId

  • inputFields: 定义用于变异的输入结构,其中输入字段将用输入值包装

  • outputFields: 定义变异完成后字段的输出结构,我们可以查看和读取

  • mutateAndGetPayload:这个函数是中继mutation的核心函数,它执行mutaion逻辑(比如数据库操作),并将返回的payload暴露给mutation的输出字段。

mutateAndGetPayload使用变异操作将输入字段映射到输出字段。它接收的第一个参数是输入参数的列表,我们可以读取它来执行变异操作

我们返回的对象mutateAndGetPayload可以resolve()作为第一个参数在输出字段函数中访问 。


getFatQuery() 是我们使用 GraphQL 片段表示数据模型中所有可能因这种突变而改变的地方