iT邦幫忙

第 11 屆 iThome 鐵人賽

0
Modern Web

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

Day16. 實作GraphQL by Ruby on rails ( 修改mutation ) (六)

mutation的部分,除了需要修改原先的CreatePost,還相新增一個RemovePost來刪除文章

修改完的程式碼如下:

app/graphql/type/mutation_type.rb

module Types
  class MutationType < BaseObject
    field :create_post, mutation: Mutations::CreatePost
    field :remove_post, mutation: Mutations::RemovePost
  end
end

app/graphql/mutations/create_post.rb

module Mutations
  class CreatePost < BaseMutation
    argument :title, String, required: true
    argument :content, String, required: true
    argument :type, Integer, required: true
    
    #回傳的type類型為PostType
    type Types::PostType
  
    def resolve(title: nil, content: nil, type: nil)
      new_post = Post.create!(
        title: title,
        content: content,
        type: Type.find(type),
      )
      return {
        id: new_post.id,
        title: title,
        content: content,
        type: Type.find(type).name,
      }      
    end
  end
end

app/graphql/mutations/remove_post.rb

module Mutations
  class RemovePost < BaseMutation
    argument :id, Integer, required: true  
    
    #回傳String
    type String
    
    def resolve(id: nil)
      if(Post.find(id).destroy)
        return "刪除成功"
      end   
    end
  end
end

使用結果如下:
https://ithelp.ithome.com.tw/upload/images/20191017/20111629vJ2BaARp5l.png

https://ithelp.ithome.com.tw/upload/images/20191017/20111629uSbiN4VqYh.png


rails的部分基本上就到此為止,我也不算是十分熟悉,但經過這次,的確更清楚GraphQL API的撰寫方法及原理了。
下個部分,我們回到Gatsby,試著從Gatsby上去抓取我們GraphQL server上的文章資料!

原始碼


上一篇
Day15. 實作GraphQL by Ruby on rails ( 修改query ) (五)
下一篇
Day17. 在Gatsby中串接第三方 GraphQL APIs
系列文
用Gatsby.js做出一個簡單的部落格28
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
ninten
iT邦新手 5 級 ‧ 2019-10-25 09:54:13

argument :type, String, required: true

type 應該是Integer

/images/emoticon/emoticon12.gif加油~很棒的主題

希望能完整寫完30天

哈哈 好的 修改完畢

第一次寫這種文章,所以內容編排跟文法可能都還蠻亂的
感謝支持XD

我要留言

立即登入留言