新手问题 graphql 的 mutation 参数搞不明白了

lukefan · January 01, 2021 · Last by 1c7 replied at June 08, 2021 · 932 hits

以前写过一些 graphql 的小练习,只用过 query,这是第一次用 mutation 去尝试更新数据。

我使用的是 gem 'graphql', '~> 1.11.6'

使用 rails g graphql:mutation Add_Person

创建了相关文件,然后去修改 add_person.rb

module Mutations
  class AddPerson < BaseMutation
    # TODO: define return fields
    # field :post, Types::PostType, null: false
    field :person, Types::PersonType, null: false

    # TODO: define arguments
    # argument :name, String, required: true
    argument :name, String, required: true
    argument :age, Integer, required: true
    argument :description, String, required: false

    def resolve(name: , age: , description: )
      person = Person.create!(name: name, age: age, description: description)
    end
    # TODO: define resolve method
    # def resolve(name:)
    #   { post: ... }
    # end
  end
end

遇到的问题是:

输入的参数,只有一个 AddPersonInput 类型的,叫做 input 的参数。我定义的 name、age、description 什么的都没有了。这是怎么个玩儿法?如果生写,就会报错,说是 input 定义了,但是没有填写。

在网上查了一下,没有看到更多的东西了。

另外,我看到网上的一些例子里面定义的 Type,都是继承自 Node,而我是用 rails g graphql:object 做的,所以都是继承自 object。不知道有什么差异。

我使用下面这个 mutition 字符串倒是成功的将数据添加进去了,只是觉得好麻烦,好诡异。 并且得到了一个报错,说是 person 没有被实现过。

为什么网上的案例都是直接输参数,我的却要用 input 包裹一下呢?

mutation{addPerson(input:{
  name: "张三",
  age: 25,
  description: "2021要更加有趣。"
}){
  person{
    id
    name
    age
    description
  }
}

}

person 没有实现的问题解决了。

这个东西很傻。

我一开始写成了这样,结果报错。

def resolve(name: , age: , description: )
   person = Person.create!(name: name, age: age, description: description)
 end

然后写成了

def resolve(name: , age: , description: )
   person: Person.create!(name: name, age: age, description: description)
 end

说是语法结构错误。 最后改成了:

def resolve(name: , age: , description: )
   person = Person.create!(name: name, age: age, description: description)
   {
     person: person,
   }
 end

可以跑了,实在是奇葩啊。

input 嵌套的问题,还是没有解决,求大神帮忙。

module Mutations
  class AddPerson < BaseMutation
    # TODO: define return fields
    # field :post, Types::PostType, null: false
    field :person, Types::PersonType, null: false

注意这里 field :person 意思就是这个 mutation 跑完之后要返回一个 person,
并且写了 null: false 不为空。所以当然会报错。
(你必须返回一个 person)

我建议你用

这俩提供的自动提示,来帮助你写 Mutation(这俩工具二选一就行,喜欢哪个用哪个)

这个问题是 2021年01月01日 提出的,现在是 2021年6月8号,我猜测这个问题你八成早就解决了

You need to Sign in before reply, if you don't have an account, please Sign up first.