1. はじめに
GraphQLとRailsを使用してTo-doアプリのAPIを構築する方法を紹介します。GraphQLは柔軟で効率的なAPIを作成するための強力なツールであり、Railsと組み合わせることで、迅速かつ堅牢なアプリケーション開発が可能になります。
2. プロジェクトのセットアップ
まず、新しいRailsプロジェクトを作成し、必要な依存関係をインストールします。
rails new todo_graphql_api --api -T -d postgresql
cd todo_graphql_api
Gemfileに以下の行を追加します:
gem 'graphql'
gem 'graphiql-rails'
そして、依存関係をインストールします:
bundle install
GraphQLをセットアップします:
rails generate graphql:install
3. モデルの作成
To-doアイテムを表すモデルを作成します:
rails g model Todo title:string description:text completed:boolean
rails db:migrate
4. GraphQLタイプの定義
app/graphql/types/todo_type.rb
に以下のコードを追加します:
module Types
class TodoType < Types::BaseObject
field :id, ID, null: false
field :title, String, null: false
field :description, String, null: true
field :completed, Boolean, null: false
field :created_at, GraphQL::Types::ISO8601DateTime, null: false
field :updated_at, GraphQL::Types::ISO8601DateTime, null: false
end
end
5. クエリの実装
app/graphql/types/query_type.rb
を以下のように更新します:
module Types
class QueryType < Types::BaseObject
field :todos, [Types::TodoType], null: false
field :todo, Types::TodoType, null: false do
argument :id, ID, required: true
end
def todos
Todo.all
end
def todo(id:)
Todo.find(id)
end
end
end
6. ミューテーションの実装
app/graphql/mutations/create_todo.rb
を作成し、以下のコードを追加します:
module Mutations
class CreateTodo < BaseMutation
argument :title, String, required: true
argument :description, String, required: false
field :todo, Types::TodoType, null: false
field :errors, [String], null: false
def resolve(title:, description: nil)
todo = Todo.new(title: title, description: description, completed: false)
if todo.save
{
todo: todo,
errors: []
}
else
{
todo: nil,
errors: todo.errors.full_messages
}
end
end
end
end
app/graphql/types/mutation_type.rb
を更新します:
module Types
class MutationType < Types::BaseObject
field :create_todo, mutation: Mutations::CreateTodo
end
end
7. GraphiQLの設定とテスト
config/routes.rb
に以下を追加します:
Rails.application.routes.draw do
post "/graphql", to: "graphql#execute"
if Rails.env.development?
mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "graphql#execute"
end
end
サーバーを起動し、GraphiQLインターフェースにアクセスします:
rails s
ブラウザでhttp://localhost:3000/graphiql
にアクセスし、以下のクエリとミューテーションをテストします:
# すべてのTodoを取得
query {
todos {
id
title
description
completed
}
}
# 新しいTodoを作成
mutation {
createTodo(input: {title: "GraphQLを学ぶ", description: "Rails with GraphQLチュートリアルを完了する"}) {
todo {
id
title
description
completed
}
errors
}
}
以上で、GraphQLとRailsを使用した基本的なTo-doアプリのAPIが完成しました。このアプリケーションをベースに、更新や削除の機能を追加したり、認証を実装したりすることで、より完全なアプリケーションに発展させることができます