ectoabsinthe

How do I set up an Absinthe schema with field names different than underlying Ecto field names?


For example, I'd like to call the inserted_on timestamp created_at in the front end in the following Absinthe schema:

defmodule MyAppWeb.Schema.AccountTypes do
  use Absinthe.Schema.Notation

  object :user do
    field :id, :id
    field :email, :string
    field :inserted_on, :datetime
  end
end

but I'm not sure how to setup the Ecto <-> Absinthe mapping. Should I just add a virtual field to my Ecto schema?


Solution

  • One option would be to use the :source option in Ecto schemas for database fields, so you can use your own internal name:

    defmodule MyAppWeb.Schema.AccountTypes do
      use Absinthe.Schema.Notation
    
      object :user do
        field :id, :id
        field :email, :string
        field :created_at, :datetime, source: :inserted_on
      end
    end
    

    But the best option would probably be to set the proper field name in the query macro:

    defmodule My.Schema do
      use Absinthe.Schema
      query do
        field :created_at, :string do
          resolve &MyResolver.inserted_on/3
      end
    end
    

    .. or use your own datatype instead of string..