iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 12
0
Modern Web

用Gatsby.js做出一個簡單的部落格系列 第 12

Day12. 實作GraphQL by Ruby on rails ( Mutation ) (三)

在graphQL中,假如我們要去修改資料或是新增資料,我們會使用到mutation這個type而非query。

今天,我們在mutation下做一個新增Post的功能:

  • 在mutation下,我們加入一個create_post的field,第二個參數,則是一個指向CreatePost的hash,而CreatePost這個mutation會放在app/graphql/mutationsmutations下,並且繼承了BaseMutation這個類別。
    app/graphql/types/mutation_type.rb
module Types
  class MutationType < BaseObject
    field :create_post, mutation: Mutations::CreatePost
  end
end
  • 此外,在/app/graphql/專案名稱_schema.rb中,必須確定有將mutation加入,不然會無法使用。
class GraphqlApiSchema < GraphQL::Schema
  mutation(Types::MutationType)
  query(Types::QueryType)
end
  • 新增app/graphql/mutations/base_mutation.rb以及app/graphql/mutations/create_post.rb,其中BaseMutation是讓CreatePost繼承的。
module Mutations
  class BaseMutation < GraphQL::Schema::Mutation
    null false
  end
end
module Mutations
  class CreatePost < BaseMutation
    argument :title, String, required: true
    argument :content, String, required: true
  
    type Types::PostType
  
    def resolve(title: nil, content: nil)
      Post.create!(
        title: title,
        content: content,
      )
    end
  end
end

在CreatePost中,用了argument方法去定義了mutation中參數的型別以及是否必填,type方法定義了回傳的type,而在resolve方法中,實現了新增功能,以及回傳我們新增的資料,這兩件事。

  • 最後,將create_post加入mutation的field中
    app/graphql/types/mutation_type.rb
module Types
  class MutationType < BaseObject
    field :create_post, mutation: Mutations::CreatePost
  end
end

於是,一個簡單的mutation便完成了。

在graphiql中,我們輸入以下查詢:

mutation {
  createPost (
    title: 'new title',
    content: 'new content',
  ){
    title
    content
  }
}

便會完成新增資料,以及回傳新增的資料。


上一篇
Day11. 實作GraphQL by Ruby on rails ( Schema chema 和 Query ) (二)
下一篇
Day13. 更新公告
系列文
用Gatsby.js做出一個簡單的部落格28
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言