elixir - Absinthe 无法序列化嵌套映射,但它能够序列化顶级映射

标签 elixir ecto absinthe

我正在尝试解析以下内容(这是我的解析器函数的返回值,我将其传递给 resolve 宏):

 {:ok,
 %{
   collection: nil,
   errors: %{
     recoverable: [
       %{
         __exception__: true,
         __recoverable__: true,
         message: %{
           color: %{
             exterior: ["is invalid"], 
             interior: ["is invalid"]
           }
         },
         type: :vehicle_invalid
       }
     ],
     unrecoverable: []
   }
 }}

这会返回这个经典错误:

** (Protocol.UndefinedError) protocol String.Chars not implemented for %{color: %{exterior: ["is invalid"], interior: ["is invalid"]}} of type Map. This protocol is implemented for the following type(s): Money, Postgrex.Copy, Postgrex.Query, Floki.Selector.AttributeSelector, Floki.Selector, Floki.Selector.Functional, Floki.Selector.Combinator, Floki.Selector.PseudoClass, Decimal, Float, DateTime, Time, List, Version.Requirement, Atom, Integer, Version, Date, BitString, NaiveDateTime, URI

据我所知,它不知道如何将 map 转换为字符串,但这引出了我的实际问题:

我想知道为什么顶级 errors map 可以很好地解析,但不能解析嵌套的 messages map ,希望得到一些指导,谢谢!

注意:我们的模式是让 Ecto 样式验证错误返回到我们自己的数据下,而不是顶级图形查询错误,因此使用 :ok 元组而不是解析 :error 元组

最佳答案

嗯,这实际上是非常明显的事情,在我的图形模式中,我将 :message 字段指定为 :string 类型,并且......它显然是一个 map 。我想我会保留这篇文章,以防万一其他人做了类似的明显的事情,这对他们有帮助,哈哈。

我可以为那些后续的人提供一些选择:

  • 让我的 :message 字段成为某种实现 String.Chars 协议(protocol)的结构,允许我将其一直传递到图形模式,将该字段保留为 :string 类型,然后当图对其调用 to_string 时,它会隐式地自行处理它。
  • 我可以定义一个自定义标量来指定序列化 https://hexdocs.pm/absinthe/Absinthe.Schema.Notation.html#serialize/1函数在退出时解析 :message 值,但这可能需要将图形模式与底层结构耦合得太紧密
  • 只需将我的 map 的 :message 值设置为字符串...

关于elixir - Absinthe 无法序列化嵌套映射,但它能够序列化顶级映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63363979/

相关文章:

phoenix-framework - 英雄联盟 : reinitialize database for Phoenix

elixir - Absinthe 后端的正确 GraphQL 查询中的未知参数

Elixir 实用函数根据索引和大小从 List 返回子列表

elixir - 引脚 (^) 运算符的使用困惑

elixir - 如何中断(无限)流?

elixir - Phoenix 框架 : mix test fails with argumenterror on new app

elixir - Ecto.Queryable 未针对用户/Phoenix 错误实现

postgresql - Ecto 加入返回 nil 记录