[英]Representing Elixir/Ecto associations in GraphQL with absinthe
我已经为我的几个模型添加了多对多的关联,并且它似乎在隔离中运行良好——这意味着没有 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
找到了示例代码,但我根本无法dataloader
工作。
我感谢你们的任何想法和想法! 谢谢
您将需要(已弃用) Absinthe.Ecto包,或者使用新的Dataloader 。 Absinthe on Ecto 最佳实践的文档中有一节介绍了使用 dataloader https://hexdocs.pm/absinthe/ecto.html#dataloader的新语法。 由于这还需要添加到您的上下文中,因此在此处添加完整的设置太多了,但文档非常好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.