Chap7 Mutation(UPDATE)

Todo in this chapter

  • implement the feature to update post

https://graphql-ruby.org/schema/generators.html#scaffolding-mutations

Step1. Create update_post mutation

terminal

rails g graphql:mutation update_post
Running via Spring preloader in process 66514
       exist  app/graphql/mutations
   identical  app/graphql/mutations/.keep
        skip  app/graphql/types/mutation_type.rb
add_root_type  mutation
      create  app/graphql/mutations/update_post.rb
        gsub  app/graphql/types/mutation_type.rb

Step2. modify update_post.rb

01

  • Imitate and modify code...

mutations/update_post.rb

module Mutations
  # Don't forget to change to Mutations::BaseMutation
  class UpdatePost < Mutations::BaseMutation
    # Define what type of value to be returned
    field :post, Types::PostType, null: false

    # Define what argument this mutation accepts
    argument :id, ID, required: true    # Here we use input objects for practice, Explain soon!
    argument :attributes, Types::PostAttributes, required: true

    def resolve(id:, attributes:)
      post = Post.find(id)
      if post.update(attributes.to_h)
        { post: post }
      else
        raise GraphQL::ExecutionError, post.errors.full_messages.join(", ")
      end
    end
  end
end

Step3. Define PostAttributes

  • You can find similar example here:

https://graphql-ruby.org/type_definitions/input_objects.html#defining-input-object-types

02

  • Create new file graphql/types/post_attributes.rb

    module Types
      class PostAttributes < Types::BaseInputObject
        description "Attributes for creating or updating a blog post"
        argument :title, String, "Header for the post", required: true
        argument :body, String, "Full body of the post", required: true
      end
    end
    

  • You can refactor create_post.rb to use PostAttributes

Step4. Test it!

03