Graphql-ruby mutations
From wikinotes
Mutations are graphql fields that trigger side effects.
- mutations return a hash, that contains all of the fields defined on it.
- mutations may optionally accept arguments
Documentation
official docs https://graphql-ruby.org/guides#mutations-guides
Basics
Set the root-mutation object on the schema
class MyGraph < GraphQL::Schema mutation(MutationRoot) endAdd your mutations as fields on the mutation-root
(field args set on mutation object)class MutationRoot < GraphQL::Schema::Object field :write_file, mutation: Mutations::WriteFile endDefine your mutation
require 'graphql' require 'digest' module Mutations class WriteFile < GraphQL::Schema::Mutation argument :path, String, required: true argument :contents, String, required: true field :checksum, String, null: false field :existed_before_write, Boolean, null: false def resolve(path:, contents:) abspath = File.expand_path(path) existed_before_write = File.exist?(abspath) write_file(abspath, contents) { checksum: file_checksum(abspath), existed_before_write: existed_before_write, } end private def write_file(path, contents) dirpath = File.dirname(path) Dir.mkdir(dirpath) unless Dir.exist?(dirpath) File.open(path, "w") do |fd| fd.write(contents) end end def file_checksum(path) File.open(path, "r") do |fd| Digest::MD5.hexdigest(fd.read) end end end endNow you can execute your mutation.
(note that fields converted from snake_case to camelCase).mutation { writeFile(path: "~/foo.txt", contents: "boo!") { checksum existedBeforeWrite } }