Rails & Nuxt.jsのアプリケーションにGraphQLを導入する

Rails と Nuxt.js で構成されたアプリケーションに GraphQL を導入します。 簡略化のためモデル作成や認証はせず、動作確認まで行います。


前提

Rails & Nuxt.jsのDocker環境をalpineイメージで構築する
こちらのポストの環境をもとに進めるので、Docker のサービス名等は適宜読み替えていただくようにお願いします。

ディレクトリ構成
後述のコマンドでは、Rails は backend、Nuxt は frontend が Docker のサービス名になっています。

.
├── backend <- Ruby on Rails
│   ├── Dockerfile
│   ├── Gemfile
│   ├── Gemfile.lock
│   (中略)
│  
├── frontend <- Nuxt.js
│   ├── Dockerfile
│   ├── README.md
│   ├── nuxt.config.js
│   ├── package-lock.json
│   ├── package.json
│  (中略)

├── docker-compose.yml
└── .env

ライブラリ追加

Rails

Gemfile を修正し、 bundle install します。

## 中略 ##

gem 'graphql' # 追加

group :development do
gem 'listen', '>= 3.0.5', '< 3.2'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'

gem 'graphiql-rails' # 追加
end

## 中略 ##
docker-compose exec backend bundle install

Nuxt

こちらのライブラリをインストールします。
本記事では graphql-tag は使いません。

docker-compose exec frontend yarn add @nuxtjs/apollo

実装

backend(rails)

generator で雛形を作成します。

docker-compose exec backend rails g graphql:install

graphiql-rails の Readme にしたがって、Rails の config ファイルを修正します。

Rails.application.routes.draw do
post "/graphql", to: "graphql#execute" #generatorでinsertされる
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html

#added
if Rails.env.development?
mount GraphiQL::Rails::Engine, at: '/graphiql', graphql_path: '/graphql'
end
end
## 中略 ##

- # require "sprockets/railtie"
+ require "sprockets/railtie"

## 中略 ##

GraphiQLで動作確認

docker コンテナを再起動後、ブラウザで http://localhost:3000/graphiql にアクセスし、GraphiQL を開きます。
app/graphql/types/query_type.rb のサンプルを利用して、下記のように query の結果が返ってくれば OK です。

docker-compose restart backend

graphiql

frontend(nuxt)

Nuxt アプリのルートに、下記のディレクトリ、ファイルを追加、編集します。
今回 mutation は使いませんが、あわせて作成しておきます。

.
└── frontend
    ├── nuxt.config.js
    │
    ├── pages
    │   └── index.vue
    │
    └── apollo
        ├── client-configs
        │   └── default.js
        └── gqls
            ├── mutations
            └── queries
                └── getTestField.gql
export default {

/* 中略 */

modules: [
'@nuxtjs/apollo', //added
],

/* 中略 */

apollo: {
clientConfigs: {
default: '~/apollo/client-configs/default.js'
}
}
}
import { HttpLink } from 'apollo-link-http'

export default () => {
const httpLink = new HttpLink({ uri: 'http://backend:3000/graphql' })
return {
link: httpLink
}
}
query {
testField
}
<template>
<p>{{ testField }}</p>
</template>

<script>
import testField from '~/apollo/gqls/queries/testField';

export default {
data() {
return {
testField: {}
}
},
apollo: {
testField: {
query: testField
}
}
}
</script>

nuxt


お疲れさまでした。
(簡略化しすぎた感)

← Blog