我试图在我的 graphql 实现中接收 JSON 字符串,但我定义的用于处理 JSON 的自定义标量不断出现错误。
我已经定义了一个自定义标量,以将 JSON 正确序列化为长生不老药映射。在我的代码到达自定义标量的解析阶段之前,我收到错误数据类型无效。我正在尝试使用https://github.com/absinthe-graphql/absinthe/wiki/Scalar-Recipes#json-using-jason创建标量,但是我已修改为使用 Poison 而不是 Jason。
我的苦艾酒使用我创建的 :json 标量类型。
@desc "Update user"
field :update_user, type: :user do
arg(:email, :string)
arg(:password, :string)
arg(:first_name, :string)
arg(:last_name, :string)
arg(:age, :integer)
arg(:client_store, :json)
resolve(handle_errors(&Resolvers.User_Resolver.update_user/3))
end
我的标量定义和 graphql 模式定义
scalar :json, name: "Json" do
description("""
The `Json` scalar type represents arbitrary json string data, represented as UTF-8
character sequences. The Json type is most often used to represent a free-form
human-readable json string.
""")
serialize(&encode/1)
parse(&decode/1)
end
# @spec decode(Absinthe.Blueprint.Input.String.t) :: {:ok, :string} | :error
# @spec decode(Absinthe.Blueprint.Input.Null.t) :: {:ok, nil}
defp decode(%Absinthe.Blueprint.Input.String{value: value}) do
Logger.info "decoded input value:"
case Poison.decode(value) do
{:ok, result} -> {:ok, result}
_ -> :error
end
end
defp decode(%Absinthe.Blueprint.Input.Null{}) do
{:ok, nil}
end
defp decode(_) do
:error
end
defp encode(value), do: value
object :user do
field(:id, :id)
field(:email, :string)
field(:password, :string)
field(:first_name, :string)
field(:last_name, :string)
field(:age, :integer)
field(:client_store, :json)
end
发送以下查询时:
mutation updateUser{
updateUser(client_store: "{"key":"value"}"){
id
}
}
我收到一个syntax error before: \"\\\":\\\"\"
mutation updateUser{
updateUser(client_store: "hello"){
id
}
}
我收到一个"Argument \"client_store\" has invalid value \"hello\"
通过单元测试发送 GraphQL 查询Phoenix.ConnTest
query = """
mutation updateUser{
updateUser(client_store: "{\"key\":\"value\"}"){
id
}
}
"""
res =
context.conn
|> put_req_header("content-type", "text")
|> put_req_header("authorization", token)
|> post("/api", query)