iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 11
0
Modern Web

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

Day11. 實作GraphQL by Ruby on rails ( Schema chema 和 Query ) (二)

在做出api前,先做出我們的model,負責資料的存取。

rails generate model Post title:string content:text
rails db:migrate

Post這個model我們先訂兩個欄位,一個是文章的標題,另一個是內容,作為存放部落格文章使用。

接著,在console下執行:

rails c

進入rails的環境,在這裡可以直接輸入指令做執行,我們在這邊新增文章資料:

Post.create title: 'first post', content: 'first content'
Post.create title: 'second post', content: 'second content'
Post.all ///抓出所有Post資料,並顯示
exit

成功新增資料後,你應該可以在畫面上看到新增的資料。

  • 首先,我們先去定義我們文章Post的Object type的內部結構,這邊值得注意的是,field並不能放入Text當作參數,所以必須用String。
    而class的撰寫方式,就是用field方法,配合我們Post model的欄位名field的scalar type型別,和是否可為空,作為三個引數,來定義我們的schema的架構。
    app/graphql/types/post_type.rb
module Types
  class PostType < BaseObject
    field :id, ID, null: false
    field :title, String, null: false
    field :content, String, null: false
  end
end

再來是定義query type,也就是查詢語法都在這邊定義。
首先,一樣是用field方法,來將all_posts加進query中,而all_posts的內容,會是由Post這個Type所形成的陣列。
然後在下方直接定義all_posts方法,其中抓出來的資料會和PostType去做匹配。
app/graphql/types/query_type.rb

module Types
  class QueryType < BaseObject
    field :all_posts, [PostType], null: false

    def all_posts
      Post.all
    end
  end
end

至此,所們便已完成了一個最簡單的query功能了。

在http://localhost:3000/graphiql 中,我們可以利用graphiql這套好用的工具,直接去進行graphql的語法查詢。

例如:

query{
 allPosts {
  title
  content
 }
}

按下執行,應該就會在右邊顯示抓到的資料了。


上一篇
Day10. 實作GraphQL by Ruby on rails ( 環境安裝 ) (一)
下一篇
Day12. 實作GraphQL by Ruby on rails ( Mutation ) (三)
系列文
用Gatsby.js做出一個簡單的部落格28
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
ninten
iT邦新手 5 級 ‧ 2019-10-24 16:12:49

最後面的graphql有錯誤提醒,應該要改成

query{
 allPosts {
  title
  content
 }
}

才抓的到資料

https://ithelp.ithome.com.tw/upload/images/20191024/20113667COz0VHGzLZ.png

https://ithelp.ithome.com.tw/upload/images/20191024/20113667obydvi0GS2.png

感謝糾正/images/emoticon/emoticon02.gif

我要留言

立即登入留言