没有子节的GraphQL变异

But*_*GOL 19 graphql graphql-js

我想发送没有子节的graphql变异请求

mutation _ {
    updateCurrentUser(fullName: "Syava", email: "fake@gmail.com")
}
Run Code Online (Sandbox Code Playgroud)

我正在接受

{
  "errors": [
    {
      "message": "Field \"updateCurrentUser\" of type \"User\" must have a sub selection.",
      ... 
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

添加{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;
  },
Run Code Online (Sandbox Code Playgroud)

Pet*_*ela 11

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

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

如果您不希望变异返回User,则可以将其类型声明为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
  }
}
Run Code Online (Sandbox Code Playgroud)