0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

本番API server に graphql を段階導入

Posted at

@_nishisuke です!

フリーランスやってます!

ある案件で本番iosのAPI serverとして既に動いてる rails にgraphqlを導入しました。

(この案件では実装の全権限をもらってます。)

いきなりclient側の実装を変えるのは変更が大きすぎると判断しました。

第一段階としてサーバーのシリアライザーレイヤーだけをgraphqlに置き換えようとしました。

api serverはrequest specが書いてあり、json-schemaによりresponse jsonが担保されています。

一部の読み込みqueryだけをターゲットにし書き込み処理は最初のスコープに入れませんでした。

rails で graphql

install

gem 'graphql'

before

app/controllers/users_controller.rb
class UsersController < ApplicationController
  def index
    user = User.where(適当なコンディション).includes(適当なアソシエーション)
    render json: UserSerializer(user)
  end
end

after

app/controllers/users_controller.rb
class UsersController < ApplicationController
  USER_SCHEMA = <<~USER_SCHEMA
    {
      users { name }
    }
  USER_SCHEMA

  def index
    gql_res = MyApplicationSchema.execute(USER_SCHEMA).to_h

    raise SomeError unless gql_res['errors'].nil?

    render json: gql_res.to_json
  end
end

結果

serializer layerだけ変えたかったが、controllerも変更を余儀なくされました。
MVC -> M + graphql
のイメージです。

gemの注意点

  • graphql-rubyのqueryはdefaultでcamelcase
  • graphql-rubyは200 statusでerror jsonを返そうとする

所感

思ったより簡単にできた。
実態と実装の構造が近くなって、変更を加えるのが容易になった。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?