如何设置字段名称与底层 Ecto 字段名称不同的 Absinthe 模式?

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

例如,我想在以下 Absinthe 架构中调用前端的 inserted_on 时间戳 created_at

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

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

但我不确定如何设置 Ecto <-> Absinthe 映射。我应该只向我的 Ecto 模式添加一个虚拟字段吗?

一种选择是在数据库字段的 Ecto 模式中使用 :source 选项,因此您可以使用自己的内部名称:

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

但最好的选择可能是在查询宏中设置正确的字段名称:

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

.. 或使用您自己的数据类型而不是字符串..