苦艾酒无法序列化嵌套地图,但可以序列化顶层地图

问题描述

我正在尝试解决以下问题(这是我的解析器函数的返回值,并将其传递给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

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

我想知道为什么可以很好地解析顶级errors地图,但不能嵌套messages嵌套地图,需要一些指导,谢谢!

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

解决方法

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

以下是我可以选择的几个选项:

  • 让我的:message字段成为实现String.Chars协议的某种结构,使我可以将其一直传递到图模式,而将该字段保留为{{1 }}类型,然后当图对此调用:string时,它会隐式处理自身。
  • 我可以定义一个自定义标量,该标量指定一个to_string https://hexdocs.pm/absinthe/Absinthe.Schema.Notation.html#serialize/1函数来解析出途中的serialize值,但这可能会导致将图模式紧密地耦合到底层结构
  • 只需让我地图的:message值是一个字符串...