我需要帮助理解Relay OutputFields,getFatQuery

时间:2017-04-16 04:54:11

标签: graphql relayjs relay graphql-js

这是来自官方继电器文档的代码,这是针对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};
  },
});

我认为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,
      },
    };
  }
}

我认为todoEdge来自GraphQL的outputFields?我看到一个查看器查询,为什么需要查询查看器?如何创建getFatQuery?如果有人帮助我更多地了解接力突变,我真的很感激。

1 个答案:

答案 0 :(得分:2)

mutateAndGetPayload 执行然后将payload返回到outputFields

mutationWithClientMutationId

Source-Code

starWarsSchema example

mutationWithClientMutationId

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

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

  • mutateAndGetPayload:此函数是中继突变的核心,它执行突变逻辑(例如数据库操作)并将返回有效负载以暴露给突变的输出字段。

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

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

getFatQuery()是我们使用GraphQL片段代表所有内容的地方 在我们的数据模型中,这种变化可能会发生变化

相关问题