Getting Started With GraphQL

View Source

Get familiar with Ash resources

If you haven't already, read the Ash Getting Started Guide. This assumes that you already have resources set up, and only gives you the steps to add AshGraphql to your resources/domains.

Installation

mix igniter.install ash_graphql

Select domains to show in your GraphQL

In the use AshGraphql call in your schema, you specify which domains you want to expose in your GraphQL API. Add any domains that will have AshGraphql queries/mutations to the domains list. For example:

use AshGraphql, domains: [Your.Domain1, Your.Domain2]

Adding Queries and Mutations

Some example queries/mutations are shown below. If no queries/mutations are added, nothing will show up in the GraphQL API, so be sure to set one up if you want to try it out.

Queries & Mutations on the Domain

Here we show queries and mutations being added to the domain, but you can also define them on the resource. See below for an equivalent definition. Prefer to add to the domain so your interface is defined in one place.

defmodule Helpdesk.Support.Ticket do
  use Ash.Resource,
    ...,
    extensions: [
      AshGraphql.Resource
    ]

  # The resource still determines its type, and any other resource/type-based
  # configuration
  graphql do
    type :ticket
  end

  ...
end

defmodule Helpdesk.Support do
  use Ash.Domain,
    extensions: [
      AshGraphql.Domain
    ]

  ...
  graphql do
    queries do
      # create a field called `get_ticket` that uses the `read` read action to fetch a single ticke
      get Helpdesk.Support.Ticket, :get_ticket, :read

      # create a field called `most_important_ticket` that uses the `most_important` read action to fetch a single record
      read_one Helpdesk.Support.Ticket, :most_important_ticket, :most_important

      # create a field called `list_tickets` that uses the `read` read action to fetch a list of tickets
      list Helpdesk.Support.Ticket, :list_tickets, :read
    end

    mutations do
      create Helpdesk.Support.Ticket, :create_ticket, :create
      update Helpdesk.Support.Ticket, :update_ticket, :update
      destroy Helpdesk.Support.Ticket, :destroy_ticket, :destroy
    end
  end
end

Queries & Mutations on the Resource

defmodule Helpdesk.Support.Ticket do
  use Ash.Resource,
    ...,
    extensions: [
      AshGraphql.Resource
    ]

  graphql do
    type :ticket

    queries do
      get :get_ticket, :read
      read_one :most_important_ticket, :most_important
      list :list_tickets, :read
    end

    mutations do
      create :create_ticket, :create
      update :update_ticket, :update
      destroy :destroy_ticket, :destroy
    end
  end

  ...
end

What's next?

Topics:

How Tos: