我有一个Elixir API,可以使用Graphiql向我的数据库发送查询,如您所见,所有crud调用都工作正常。
field :users, list_of(:user) do
resolve &Graphical.UserResolver.all/2
end
这将从数据库返回所有用户。现在显然,如果您使用前端,这并不理想,您不想手动键入查询。我将如何实现在架构文件中调用这些字段的函数?我怎么写说这个查询
users{
id,
name,
email
}
在 Elixir 本身中,这样我就可以从前端调用它以 JSON 格式返回所有数据。我不确定在哪里以及如何编写查询,以便将它们传递给模式,然后苦艾酒和 Ecto 负责其余的工作。
可以做点什么查询:
users(scope: "some"){}
在旋转变压器中
defmodule Graphical.UserResolver do
def all(_root, %{:scope => "some"}, _info) do
users = Graphical.Repo.all(from user in Graphical.User,
select: { user.name, user.email, user.id }
)
{:ok, users}
end
def all(_root, _args, _info) do
users = Graphical.Repo.all(Graphical.User)
{:ok, users}
end
end
当你从 FE 查询苦艾酒时,你会得到一个 JSON 对象作为回报。 如果要让字段返回 JSON 对象,则必须创建自定义标量并将其用作字段类型。例如
defmodule ApiWeb.Schema.Types.JSON do
@moduledoc """
The Json scalar type allows arbitrary JSON values to be passed in and out.
Requires `{ :jason, "~> 1.1" }` package: https://github.com/michalmuskala/jason
"""
use Absinthe.Schema.Notation
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, term()} | :error
@spec decode(Absinthe.Blueprint.Input.Null.t()) :: {:ok, nil}
defp decode(%Absinthe.Blueprint.Input.String{value: value}) do
case Jason.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
end
然后
@desc "Create an auth token"
field :create_auth_token, :token do
arg(:app_id, non_null(:string))
arg(:sub, non_null(:string))
arg(:claims, :json)
resolve(&Resolvers.Token.create_auth_token/3)
end
```