GraphQL Rubyでenumを使ってみる (Rails)

December 20, 2022

確認環境

$ bundle exec ruby --version
ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-darwin19]
$ bundle exec rails --version
Rails 6.0.4.6
$ bundle info graphql
  * graphql (2.0.13)
	Summary: A GraphQL language and runtime for Ruby
	Homepage: https://github.com/rmosolgo/graphql-ruby
	Path: /Users/xxxxx/.rbenv/versions/2.7.5/lib/ruby/gems/2.7.0/gems/graphql-2.0.13

データ準備

テーブル定義確認

$ rails db
sqlite> .schema posts
CREATE TABLE IF NOT EXISTS "posts" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar, "description" text, "created_at" datetime(6) NOT NULL, "updated_at" datetime(6) NOT NULL, "status" integer);

検証コードを実装

app/models/post.rb

class Post < ApplicationRecord
  enum status: { draft: 0, open: 1 }
end

app/graphql/types/query_type.rb

module Types
  class QueryType < Types::BaseObject
    field :posts, [Types::PostType], null: false
    def posts
      Post.all.limit(5)
    end
  end
end

app/graphql/types/post_status_enum.rb

module Types
  class PostStatusEnum < Types::BaseEnum
    value "draft"
    value "open"
  end
end

app/graphql/types/post_type.rb

# frozen_string_literal: true

module Types
  class PostType < Types::BaseObject
    global_id_field :id

    field :title, String
    field :status, Types::PostStatusEnum
    field :created_at, GraphQL::Types::ISO8601DateTime, null: false
    field :updated_at, GraphQL::Types::ISO8601DateTime, null: false
  end
end

graphiql でクエリを発行する

query {
  posts {
    title
    status
  }
}

取得結果

{
  "data": {
    "posts": [
      {
        "title": "title_0",
        "status": "draft"
      },
      {
        "title": "title_1",
        "status": "draft"
      },
      {
        "title": "title_2",
        "status": "draft"
      },
      {
        "title": "title_3",
        "status": "draft"
      },
      {
        "title": "title_4",
        "status": "open"
      }
    ]
  }
}

SHARE

Profile picture

Written by tamesuu