没有子节的GraphQL变异

时间:2015-12-03 19:56:31

标签: graphql graphql-js

我想发送没有子节

的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;
  },

1 个答案:

答案 0 :(得分:9)

您将字段的类型定义为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
  }
}