GraphQL Q&A

GraphQL Q&A

Presentation slides for the JapanTaxi x MedPeer Ruby/Rails meetup
https://medpeer.connpass.com/event/82327/

80046ac4618076c5369398b92db8f313?s=128

Yusuke Mito

April 25, 2018
Tweet

Transcript

  1. 7.
  2. 11.
  3. 14.

    POST ! create GET ! show PATCH ! update DELETE

    ! destroy 200 ! OK 400 ! Bad Request 403 ! Forbidden 404 ! Not Found
  4. 15.

    POST ! create GET ! show PATCH ! update DELETE

    ! destroy httpのメソッドやステータスをAPI表現に使わない 200 ! OK 400 ! Bad Request 403 ! Forbidden 404 ! Not Found
  5. 17.

    Post User Query user(id: 1): User post(id: 2): Post comments:

    [Comment] Post Post Post Comment Comment Comment posts: [Post] Comment Comment Comment comments: [Comment] User User user: User user: User user: User
  6. 26.

    class Schema < GraphQL::Schema query Types::QueryType end class QueryType <

    GraphQL::Schema::Object field :user, Types::UserType, null: true do argument :id, ID, required: true end def user(id:) User.find_by(id: id) end end class UserType < GraphQL::Schema::Object field :email, String, null: true field :name, String, null: false field :friends, [User], null: false end Schema QueryType UserType
  7. 27.

    class GraphqlController < ApplicationController def execute variables = ensure_hash(params[:variables]) query

    = params[:query] operation_name = params[:operationName] context = { current_user: current_user, } result = Schema.execute( query, variables: variables, context: context, operation_name: operation_name ) render json: result end end Schema.execute(query).as_json #=> Hash
  8. 30.
  9. 33.
  10. 35.

    graphql-batch class Types::CommentType < Types::BaseObject description 'Comment object' field :user,

    Types::Objects::UserType, null: false def user Loaders::RecordLoader.for(User).load(object.user_id) end end Loaderがidを内部で保持し、userの値を返す際に User.where(id: ids)で1クエリで結果を取得する https://github.com/Shopify/graphql-batch