【问题标题】:How get rid of redundant wrapper object of a mutation result?如何摆脱突变结果的冗余包装对象?
【发布时间】:2019-03-25 09:59:18
【问题描述】:

当我通过这样的突变向我的后端发出请求时:

mutation{
  resetPasswordByToken(token:"my-token"){
    id
  }
}

我收到了这样格式的回复:

{
  "data": {
    "resetPasswordByToken": {
      "id": 3
    }
  }
}

对我来说,与突变命名相同的包装器对象似乎有些尴尬(并且至少是多余的)。有没有办法摆脱那个包装器,让返回的结果更干净一些?

这就是我现在定义突变的方式:

export const ResetPasswordByTokenMutation = {
    type: UserType,
    description: 'Sets a new password and sends an informing email with the password generated',
    args: {
        token: { type: new GraphQLNonNull(GraphQLString) },
        captcha: { type: GraphQLString },
    },
    resolve: async (root, args, request) => {
        const ip = getRequestIp(request);
        const user = await Auth.resetPasswordByToken(ip, args);
        return user.toJSON();
    }
};

【问题讨论】:

    标签: graphql graphql-js


    【解决方案1】:

    一句话:没有

    resetPasswordByToken 不是“包装对象”,而只是您在架构中定义的解析为对象(在本例中为UserType)的字段。虽然一次只请求 mutation 类型上的一个字段很常见,但也可以请求任意数量的字段:

    mutation {
      resetPasswordByToken(token:"my-token"){
        id
      }
      someOtherMutation {
        # some fields here
      }
      andYetAnotherMutation {
        # some other fields here
      }
    }
    

    如果我们像您建议的那样扁平化响应的结构,我们将无法区分一种突变返回的数据与另一种突变返回的数据。我们同样需要将所有这些嵌套在 data 中,以使我们的实际数据与任何返回的错误(出现在单独的 errors 条目中)分开。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-01
      • 2022-01-01
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 2011-08-07
      • 2012-04-15
      • 2011-08-21
      相关资源
      最近更新 更多