0

我正在通过阅读 todo 示例来学习 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};
  },
});

中继突变在这里定义,并调用如下:

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
  }
}
4

1 回答 1

1

如果您想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_CHILDRENmutator 配置。

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,
          }
        `,
      ],
    }];
  }
}

要了解更多信息,请查看关于 mutation 的 Relay 文档

于 2016-06-14T16:49:43.443 回答