27

我想发送不带子部分的 graphql 变异请求

mutation _ {
    updateCurrentUser(fullName: "Syava", email: "fake@gmail.com")
}

我得到

{
  "errors": [
    {
      "message": "Field \"updateCurrentUser\" of type \"User\" must have a sub selection.",
      ... 
    }
  ]
}

添加 { id } 以请求工作正常,但我不想要

还有架构代码

const userType = new GraphQLObjectType({
  name: 'User',
  fields: () => ({
    id: { type: new GraphQLNonNull(GraphQLString) },
    fullName: { type: GraphQLString },
    email: { type: GraphQLString },
  }),
});

type: userType,
  args: {
    fullName: { type: GraphQLString },
    email: { type: new GraphQLNonNull(emailType) },
    password: { type: GraphQLString },
  },
  resolve: async (root, { fullName, email, password }, { rootValue }) => {
    const user = await User.findById(rootValue.req.user.id);

    ...

    return user;
  },
4

1 回答 1

15

您将字段的类型定义为 UserType。即使它是一个突变,它仍然遵循与查询相同的规则和行为。因为 UserType 是对象类型,所以它需要嵌套字段。

mutation _ {
  updateCurrentUser(fullName: "Syava", email: "fake@gmail.com") {
    fullName
    email
  }
}
// would respond with { fullName: 'Syava', email: 'fake@gmail.com' }

如果您不希望突变返回用户,您可以将其类型声明为 GraphQLBoolean 例如——这是一个标量并且没有任何嵌套字段。

{
  type: GraphQLBoolean,
  args: {
    fullName: { type: GraphQLString },
    email: { type: new GraphQLNonNull(emailType) },
    password: { type: GraphQLString },
  },
  resolve: async (root, { fullName, email, password }, { rootValue }) => {
    const user = await User.findById(rootValue.req.user.id);
    user.fullName = fullName;
    user.password = password; // or hashed to not store plain text passwords
    return user.save(); // assuming save returns boolean; depends on the library you use
  }
}
于 2015-12-10T03:06:47.190 回答