【问题标题】:Representing Elixir/Ecto associations in GraphQL with absinthe用苦艾酒在 GraphQL 中表示 Elixir/Ecto 关联
【发布时间】:2020-05-04 13:07:36
【问题描述】:

我已经为我的几个模型添加了多对多关联,并且它似乎在隔离时工作得很好——这意味着没有 GraphQL 模式声明。这是我的一个模型的代码:

  use Ecto.Schema
  import Ecto.Changeset

  alias Trader.Collect.Card

  schema "users" do
    field(:email, :string)
    field(:first_name, :string)
    field(:last_name, :string)
    field(:password, :string)
    field(:username, :string)

    many_to_many(:cards, Card, join_through: "user_cards")

    timestamps()
  end

  @doc false
  def changeset(user, attrs) do
    user
    |> cast(attrs, [:first_name, :last_name, :email, :username, :password])
    |> validate_required([:first_name, :last_name, :email, :username, :password])
  end
end

这里是 GraphQL 类型声明:

defmodule TraderWeb.Schema.Types.User do
  use Absinthe.Schema.Notation

  @desc "User model representation"
  object :user do
    field(:id, non_null(:id))
    field(:first_name, non_null(:string))
    field(:last_name, non_null(:string))
    field(:username, non_null(:string))
    field(:email, non_null(:string))
    field(:password, non_null(:string))
    # field(:cards, list_of(:card), resolve: assoc(:cards))
  end
end

这是 Absinthe/GraphQL 部分的顶级架构定义:

defmodule TraderWeb.Schema.Schema do
  use Absinthe.Schema

  import_types(Absinthe.Type.Custom)

  # Import Types individually here
  import_types(TraderWeb.Schema.Types.{
    User,
    Card,
    CardSet
  })

  # import queries here
  import_types(TraderWeb.Schema.Queries.{
    User,
    Card,
    CardSet
  })

  query do
    import_fields(:user_queries)
    import_fields(:card_queries)
    import_fields(:card_set_queries)
  end
end

请注意,卡片字段在类型中已被注释掉。在这种情况下一切正常,但是,如果我取消注释该卡字段,我会收到以下错误:

== Compilation error in file lib/trader_web/schema/types/user.ex ==
** (CompileError) lib/trader_web/schema/types/user.ex:12: undefined function assoc/1
    (elixir) src/elixir_locals.erl:108: :elixir_locals."-ensure_no_undefined_local/3-lc$^0/1-0-"/2
    (elixir) src/elixir_locals.erl:108: anonymous fn/3 in :elixir_locals.ensure_no_undefined_local/3
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:229: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/7

我非常积极地用谷歌搜索了这个问题,但找不到任何东西。目前还不清楚assoc 函数甚至存在于哪里——它是一个ecto 的东西吗?还是苦艾酒?我还在某处使用 dataloader 找到了示例代码,但我根本无法让它工作。

感谢大家的任何想法和想法! 谢谢

【问题讨论】:

    标签: graphql elixir associations ecto absinthe


    【解决方案1】:

    您将需要(已弃用)Absinthe.Ecto 包,或使用新的 Dataloader。 Absinthe 文档中有一个关于 Ecto 最佳实践的部分,其中描述了使用 dataloader https://hexdocs.pm/absinthe/ecto.html#dataloader 的新语法。由于这也需要添加到您的上下文中,因此在此处添加完整设置会太多,但文档非常好。

    【讨论】:

      猜你喜欢
      • 2021-07-08
      • 1970-01-01
      • 2018-12-14
      • 1970-01-01
      • 2018-12-25
      • 2018-03-19
      • 1970-01-01
      • 2021-12-15
      • 2019-02-27
      相关资源
      最近更新 更多