Skip to content

GraphQL types, queries and mutations

Easy8 uses the graphql-ruby gem. All queries, mutations and subscriptions belong to one schema, EasyGraphql::AppSchema (app/api/easy_graphql/app_schema.rb). graphiql-rails is mounted at /graphiql for trying queries.

Where the code goes

Core classes live in app/api/easy_graphql/. A plugin keeps its own classes in <plugin>/app/api/easy_graphql/ using the same sub-folders (types, resolvers, mutations, subscriptions). The legacy <plugin>/api/ folder is deprecated.

After you change the schema, regenerate the frontend schema and types: see GraphQL services and definitions.

Patch an existing GraphQL class

Keep the patch in the plugin or engine that owns the extension. For customer-specific behaviour, use a modification_<name> plugin. Use the component's existing patch root, patches/ or easy_patch/, and preserve the target component's directory context:

Target Path within the owning plugin or engine
Common GraphQL class patches/easy_graphql/... or easy_patch/easy_graphql/...
GraphQL class specific to another plugin or engine patches/<other_component>/easy_graphql/... or easy_patch/<other_component>/easy_graphql/...

For example, a patch to a GraphQL class defined by other_plugin belongs under <owner>/patches/other_plugin/easy_graphql/, not directly under <owner>/patches/easy_graphql/. Patching a common GraphQL class still uses patches/easy_graphql/, regardless of which plugin owns the extension. The directory context does not guard an optional dependency; use conditional registration when the target component may be absent.

  1. Create a named module in the appropriate directory, mirroring the target class's remaining path, for example types/my_entity_patch.rb.
  2. Declare fields or arguments inside self.included(base) using base.class_eval. Define field resolver methods as instance methods of the module; object is the underlying model.
  3. Register the target class and module as strings with EasyPatchManager.register_graphql_patch at the end of the file.

In this fictional example, assume EasyGraphql::Types::MyEntity already has a displayName field resolved by a display_name method, and its underlying model has a reference attribute. The patch adds a hasReference field and prefixes the existing display name when a reference is present:

my_plugin/patches/easy_graphql/types/my_entity_patch.rb
module MyPlugin
  module EasyGraphql
    module Types
      module MyEntityPatch

        def self.included(base)
          base.class_eval do
            field :has_reference, ::GraphQL::Types::Boolean, null: false

            alias_method_chain :display_name, :my_plugin
          end
        end

        def has_reference
          object.reference.present?
        end

        def display_name_with_my_plugin
          return display_name_without_my_plugin unless has_reference

          "#{object.reference}: #{display_name_without_my_plugin}"
        end

      end
    end
  end
end

EasyPatchManager.register_graphql_patch "EasyGraphql::Types::MyEntity", "MyPlugin::EasyGraphql::Types::MyEntityPatch"

The new hasReference field uses the module's has_reference resolver. The existing displayName field uses the wrapped display_name method, so it does not need to be declared again. Use absolute constant paths, as shown by ::GraphQL::Types::Boolean, to avoid resolving constants relative to your plugin's namespace.

Use the same pattern for other GraphQL classes:

Target Declaration inside base.class_eval
EasyGraphql::Types::Query field :my_entities, resolver: ::EasyGraphql::Resolvers::MyEntities
EasyGraphql::Types::Mutation field :create_my_entity, mutation: ::EasyGraphql::Mutations::CreateMyEntity, null: true
EasyGraphql::Types::Inputs::IssueAttributes argument :my_reference, ::GraphQL::Types::String, required: false

The resolver and mutation in the table are placeholders for classes you define in your plugin. Adding an input argument does not by itself permit updating a model attribute; preserve the mutation's authorisation and safe-attribute checks.

Loading and method overrides

Easy8 automatically requires .rb files under an active plugin's patches/ directory, including nested component directories. For engine patches, keep the engine's existing easy_patch/ loading. Do not require individual patch files from a plugin initialiser or call the deprecated EasyApi::Loader.load_api yourself. EasyGraphql::AppSchema applies legacy block patches followed by registered named patches before attaching its root types. Keep schema declarations inside the inclusion hook so patch discovery does not load the target class or build fields too early. Field extensions can instantiate queries while building the schema, not just when a request executes.

For a method-only override, register the module with prepend: true and call super when you need the original implementation. A prepended module uses self.prepended(base), not self.included(base), if it also needs a class-level hook. See Patches and cross-plugin extensions for ordering and conditional registration options.

Wrap an existing resolver with alias_method_chain

For an inclusion-based patch, use alias_method_chain to wrap a resolver method already defined on the target class. Simply defining the same method in an included module does not override a method defined directly on that class.

In the example above, the chain preserves the previous implementation as display_name_without_my_plugin and routes calls to display_name_with_my_plugin. Entities without a reference keep their original display name. Use a suffix unique to your plugin, and call the _without_... method when your custom behaviour does not apply. Keep the default inclusion registration for this pattern; do not combine alias_method_chain with prepend: true or use super as the chain's fallback.

Convert a block-based patch

The older block-based EasyGraphql.register_patch API remains supported for existing patches. Use named modules and EasyPatchManager.register_graphql_patch for new patches. When converting an old patch, remove its block registration and explicit initialiser require so the field is not declared twice. EasyGraphql.patch is deprecated.

Types

https://graphql-ruby.org/guides#type-definitions-guides

Types live in app/api/easy_graphql/types and inherit from EasyGraphql::Types::Base (types/base.rb). Declare data with field and filter arguments with argument.

ID vs. Int vs. Integer

https://graphql-ruby.org/type_definitions/scalars.html

Use ID for primary keys and relations. Use Integer for other integer values.

Enums

https://graphql-ruby.org/type_definitions/enums.html

Enums inherit from GraphQL::Schema::Enum and live in types/enums, for example EasyGraphql::Types::Enums::SortOrder. Name an enum in the singular, for example IssueStatus.

Inputs (arguments)

https://graphql-ruby.org/type_definitions/input_objects.html

An input is a hash of entity attributes, used mostly by mutations. Inputs inherit from EasyGraphql::Types::BaseInput (types/base_input.rb) and live in types/inputs. Name the file model_name_attributes.rb; the _attributes suffix distinguishes an input from a type.

Best-practice

  1. Inherit every type from Types::Base.
  2. Set the required option on every argument.
  3. Use ID for primary keys and relations, Integer for other integers.

Resolvers

https://graphql-ruby.org/fields/resolvers.html

A resolver fetches data. Inherit from EasyGraphql::Resolvers::Base (resolvers/base.rb), declare parameters with argument, the return type with type, and fetch the data in resolve.

Place resolvers in app/api/easy_graphql/resolvers. Name a resolver after what it does, or after the entity in plural when it fetches entities, for example Issues or MarkAsRead.

Best-practice

  1. Set the required option on every argument and read values through arguments.
  2. Fetch a single entity with find. ActiveRecord::RecordNotFound for a missing record is the correct outcome.
  3. Fetch only records the current user may see, for example through the visible scope.

Example

example usage of resolver
module EasyGraphql
  module Resolvers
    class IssueDetail < Resolvers::Base
      description "Return Issue object based on given ID."

      type Types::Issue, null: false

      argument :id, ID, required: true

      def resolve(**_args)
        issue
      end

      private

      def issue
        @issue ||= ::Issue.preload(journals: :details).visible.find(arguments[:id])
      end

    end
  end
end

Mutations

https://graphql-ruby.org/mutations/mutation_classes.html

A mutation changes data. Inherit from EasyGraphql::Mutations::Base (mutations/base.rb), declare inputs with argument, the returned data with field, and do the change in resolve.

Place mutations in app/api/easy_graphql/mutations. Name a mutation after what it does, or after the entity with an action prefix, for example CreateIssue, UpdateIssue or DeleteIssue.

[!CAUTION] One mutation does one action. Never combine create and update in one mutation.

Error handling

https://graphql-ruby.org/mutations/mutation_classes.html#error-handling

Errors use EasyGraphql::Types::Error (types/error.rb). Define errors on your mutation as a field:

field :errors, [Types::Error], null: true

errors must always be an array of Types::Error.

Inside a mutation, errors returns an EasyGraphql::Mutations::Errors object (mutations/errors.rb) with two methods:

app/api/easy_graphql/mutations/errors.rb
# Add an error to the errors array.
def add_error(attribute:, messages:, is_required: false)
  errors << { attribute:, messages:, is_required: }
end

# Add errors from an entity to the errors array.
def add_entity_errors(entity)
  entity_errors = EasyExtensions::ParseActiveRecordErrors.call(entity)
  errors.concat(entity_errors)
end

To save an ActiveRecord object in a mutation:

Example of resolve method with validation
entity.init_journal(User.current, "My changes")
errors.add_entity_errors(entity) unless entity.save

{ entity:, errors: }

Best-practice

  1. Prefix the mutation name with the action (Create, Update, Delete).
  2. Always return the errors field. Return an empty array when there is no error.
  3. Set the required option on every argument.
  4. Fetch an existing entity with find on a visible scope. ActiveRecord::RecordNotFound for a missing record is the correct outcome.
  5. Authorise every change. When the user lacks permission, raise Unauthorized.
  6. Call init_journal when the entity is journalised.
  7. Assign attributes with safe_attributes=.
  8. When a new entity is invalid, return errors and nil for the entity.

Mutation example

example of mutation
module EasyGraphql
  module Mutations
    # Please replace "entity" for specific object,
    # to avoid usage of mutation for multiple entities.
    class UpdateEntity < Mutations::Base
      description "Update an Entity."

      argument :id, ID, required: true
      argument :attributes, Types::Inputs::EntityAttributes, required: true

      field :entity, Types::Entity, null: false
      field :errors, [Types::Error]

      def resolve(**_args)
        raise Unauthorized unless entity.editable?

        entity.init_journal(User.current)
        entity.safe_attributes = arguments[:attributes].to_hash

        unless entity.save
          errors.add_entity_errors(entity)
        end

        { entity:, errors: }
      end

      private

      def entity
        @entity ||= Entity.visible.find(arguments[:id])
      end

    end
  end
end

Delete mutations

A delete mutation returns the least it can. Return the deleted object or its ID only when the frontend needs it; otherwise return errors alone, which tells the frontend whether the operation succeeded.

ActiveRecord#destroy succeeds even for an invalid object. A failed destroy raises ActiveRecord::RecordNotDestroyed: rescue it and return its message as an error on attribute :base.

Delete mutation example

example of delete mutation
module EasyGraphql
  module Mutations
    # Please replace "entity" for specific object,
    # to avoid usage of mutation for multiple entities.
    class DeleteEntity < Mutations::Base
      description "Destroys entity."

      argument :id, ID, required: true

      field :errors, [Types::Error], null: true

      def resolve(**_args)
        raise Unauthorized unless entity.deletable?

        entity.destroy
        { errors: }
      rescue ActiveRecord::RecordNotDestroyed => e
        errors.add_error(attribute: :base, messages: [e.message])
        { errors: }
      end

      private

      def entity
        @entity ||= Entity.visible.find(arguments[:id])
      end

    end
  end
end

Subscriptions

https://graphql-ruby.org/subscriptions/subscription_classes.html

A subscription is a channel the client opens once; the server then pushes data whenever a trigger fires. Inherit from EasyGraphql::Subscriptions::Base (subscriptions/base.rb) and place the class in app/api/easy_graphql/subscriptions. Name it after the object and the event, for example IssueUpdated.

Implement subscribe (runs once, when the client subscribes; may return initial data) and, only when needed, update (runs on every trigger; by default returns the triggered object). Do not override resolve.

Setup, registration, triggering, frontend and testing are described in Real-time updates.