iT邦幫忙

第 11 屆 iThome 鐵人賽

0
Modern Web

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

Day15. 實作GraphQL by Ruby on rails ( 修改query ) (五)

  • 分享至 

  • twitterImage
  •  

根據Day14的新的架構,我修改我的/app/graphql/query/query_type.rb這支檔案

app/graphql/type/query_type.rb

module Types
  class QueryType < BaseObject

    field :all_posts, [PostType], null: false
    field :find_post, PostType, null: false do
      description 'Find an post by ID'
      argument :id, ID, required: true
    end
    field :find_posts_by_type, [PostType], null: false do
      description 'Find an post by type'
      argument :id, ID, required: true
    end

    def all_posts
      posts = Post.all
      result = posts.map {|c| {id: c.id, title: c.title, content: c.content, type: c.type.name}}
      return result
    end

    def find_post(id: id)
      post = Post.find(id)
      return {id: post.id, title: post.title, postontent: post.content, type: post.type.name}
    end

    def find_posts_by_type(id: id)
      posts = Post.where("type_id = ?", id)
      result = posts.map {|c| {id: c.id, title: c.title, content: c.content, type: c.type.name}}
      return result
    end
  end
end

光是修改這個不夠,因為我們回傳的資料是PostTypetType,但現在app/graphql/type/post_type.rb還沒有新增type這個field,所以需要修改這支檔案:
app/graphql/type/post_type.rb

module Types
  class PostType < BaseObject
    field :id, ID, null: false
    field :title, String, null: false
    field :content, String, null: false
    field :type, String, null: false
  end
end

all_posts方法,基本沒做甚麼大修改,但我們希望抓出來的資料可以顯示他的分類名稱,因此使用map方法,把他的value重新放到一個hash上面。

find_post則接收一個id,找出相對應的文章。

而find_posts_by_type接收一個id,找出相對於該id的分類的文章們,結果如下:https://ithelp.ithome.com.tw/upload/images/20191017/20111629jXGzGfTwQA.png


上一篇
Day 14. 實作GraphQL by Ruby on rails ( 修改資料表 ) (四)
下一篇
Day16. 實作GraphQL by Ruby on rails ( 修改mutation ) (六)
系列文
用Gatsby.js做出一個簡單的部落格28
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言