在中继中,如何获取 graphql 中定义的 outputFilelds?

In relay, how can I get the outputFilelds defined in graphql?

我正在通过阅读待办事项示例来学习 graphql/relay。

突变模式定义如下:

const GraphQLChangeTodoStatusMutation = mutationWithClientMutationId({
  name: 'ChangeTodoStatus',
  inputFields: {
    complete: { type: new GraphQLNonNull(GraphQLBoolean) },
    id: { type: new GraphQLNonNull(GraphQLID) },
  },
  outputFields: {
    todo: {
      type: GraphQLTodo,
      resolve: ({localTodoId}) => getTodo(localTodoId),
    },
    viewer: {
      type: GraphQLUser,
      resolve: () => getViewer(),
    },
  },
  mutateAndGetPayload: ({id, complete}) => {
    const localTodoId = fromGlobalId(id).id;
    changeTodoStatus(localTodoId, complete);
    return {localTodoId};
  },
});

中继突变已定义 here,调用方式如下:

this.props.relay.commitUpdate(
  new ChangeTodoStatusMutation({
    complete,
    todo: this.props.todo,
    viewer: this.props.viewer,
  })
);

我只是对 schmea 中的 outputFileds 从未在调用方中使用过,并且看起来与中继中的胖查询无关感到困惑。谁能详细解释一下?

无论如何,我的最终目标是在 grapahql/relay 中实现身份验证(如下所示),这需要获取突变模式中定义的输出,但我不知道如何实现。

mutation {
  createToken(username: String!, password: String!) {
    token
    error
  }
}

如果您想直接获取 outputFields,而不是使用它们来更新客户端存储,您可以定义 onSuccess 函数并通过 response 对象访问它们。

const onSuccess = response => {
    if (response.createToken.error) {
        console.log('Could not create token. Got error: ' + error);
    } else {
        // store response.createToken.token for future use.
    }
};
this.props.relay.commitUpdate(
    new CreateTokenMutation({username, password}),
    {onSuccess}
);

在您的客户端变更实现中,即 CreateTokenMutation,您必须指定 outputFields 并不意味着更新客户端存储。因此,您将使用 REQUIRED_CHILDREN 增变器配置。

class CreateTokenMutation extends Relay.Mutation {
  getMutation() {
    return Relay.QL`mutation {createToken}`;
  }

  getVariables() {
    return {
        username: this.props.username,
        password: this.props.password,
    };
  }

  getFatQuery() {
    return Relay.QL`
      fragment on CreateTokenPayload @relay(pattern: true) {
        token,
        error,
      }
    `;
  }

  getConfigs() {
    return [{
      type: REQUIRED_CHILDREN,
      children: [
        Relay.QL`
          fragment on CreateTokenPayload {
            token,
            error,
          }
        `,
      ],
    }];
  }
}

要了解更多信息,请查看 Relay documentation on mutation