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



  • graphql-ruby ... Ruby에서 GraphQL을 소개한다면 이것

  • graphiql-rails ... GraphQL IDE의 Rails 버전. 브라우저에서
  • ./backend/Gemfile 수정, bundle install.
    ## (中略) ##
    
    gem 'graphql' #added
    
    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' #added
    end
    
    ## (中略) ##
    
    $ docker-compose exec backend bundle install
    

    Nuxt


  • apollo-module

  • 이 라이브러리를 설치합니다.
    이 문서에서는 graphql-tag을 사용하지 않습니다.
    $ docker-compose exec frontend yarn add @nuxtjs/apollo
    

    구현



    Rails



    generator에서 병아리를 만듭니다.
    $ docker-compose exec backend rails g graphql:install
    

    graphiql-rails Readme에 따라 Rails config 파일을 수정합니다.

    . / 바 c 켄 d / 곤후 g / 납치 s. rb



    GraphiQL 엔진을 마운트하여 브라우저에서 액세스할 수 있도록 합니다.
    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
    

    . / 바 c 켄 d / 곤후 g / 아 p ぃ 카치온. rb



    API 모드의 경우에 필요한 수정입니다.
    ## (中略) ##
    
    - # require "sprockets/railtie"
    + require "sprockets/railtie"
    
    ## (中略) ##
    

    GraphiQL로 동작 확인



    docker 컨테이너를 다시 시작한 후 브라우저에서 http://localhost:3000/graphiql에 액세스하여 GraphiQL을 엽니다../backend/app/graphql/types/query_type.rb 의 샘플을 이용해, 아래와 같이 query의 결과가 돌려주면 OK입니다.
    $ docker-compose restart backend
    



    Nuxt



    Nuxt 앱의 루트에 다음 디렉토리, 파일을 추가하고 편집합니다.
    이번에는 mutation은 사용하지 않지만, 함께 작성해 둡니다.
    .
    └── frontend 
        ├── nuxt.config.js
        │
        ├── pages
        │   └── index.vue
        │
        └── apollo
            ├── client-configs
            │   └── default.js
            └── gqls
                ├── mutations
                └── queries
                    └── testField.gql
    

    . /f 론텐 d/누 xt. 곤후 g. js



    Nuxt에서 apollo 클라이언트를 사용하기 위한 설정을 추가합니다.default.js를 읽지 않고 nuxt.config.js에 직접 쓰는 것이 좋습니다.
    export default {
    
      /* (中略) */
    
      modules: [
        '@nuxtjs/apollo', //added
      ],
    
      /* (中略) */
    
      apollo: {
        clientConfigs: {
          default: '~/apollo/client-configs/default.js'
        }
      }
    }
    

    . / f 롱 텐 d / 아폽 / c ぃ 엔 t 콘후 ぃ gs /로 ふぁる lt. js



    apollo에는 여러가지 옵션이 있습니다만, 이번은 query의 실행을 확인할 수 있으면 좋기 때문에 최소한입니다.
    uri의 호스트 이름은 Docker의 Rails 앱 서비스 이름backend입니다.
    import { HttpLink } from 'apollo-link-http'
    
    export default () => {
      const httpLink = new HttpLink({ uri: 'http://backend:3000/graphql' })
      return {
        link: httpLink
      }
    }
    

    . / f 롱텐 d / 아폽 / gqls / 쿠에리 s / st st 푸에 ld. gql



    GraphiQL에서 실행한 것입니다.
    query {
      testField
    }
    

    . /f 롱텐 d/파게 s/이어 x.ゔ



    query를 실행한 결과를 표시합니다.
    <template>
      <p>{{ testField }}</p>
    </template>
    
    <script>
    import testField from '~/apollo/gqls/queries/testField';
    
    export default {
      data() {
        return {
          testField: {}
        }
      },
      apollo: {
        testField: {
          query: testField
        }
      }
    }
    </script>
    



    수고하셨습니다.
    (간략화 시 너무 느낌)

    좋은 웹페이지 즐겨찾기