如何从Elixir API创建GraphQL查询?
我有一个ElixirAPI,可以使用Graphiql向我的数据库发送查询,正如您所看到的,所有crud调用都工作正常如何从Elixir API创建GraphQL查询?,elixir,phoenix-framework,graphql,ecto,Elixir,Phoenix Framework,Graphql,Ecto,我有一个ElixirAPI,可以使用Graphiql向我的数据库发送查询,正如您所看到的,所有crud调用都工作正常 field :users, list_of(:user) do resolve &Graphical.UserResolver.all/2 end 这将返回数据库中的所有用户。显然,如果您使用的是前端,您不想手动键入查询,那么这并不理想。如何实现在模式文件中调用这些字段的函数?我如何写和说这个问题 users{ id, name, e
field :users, list_of(:user) do
resolve &Graphical.UserResolver.all/2
end
这将返回数据库中的所有用户。显然,如果您使用的是前端,您不想手动键入查询,那么这并不理想。如何实现在模式文件中调用这些字段的函数?我如何写和说这个问题
users{
id,
name,
email
}
在Elixir本身中,因此我可以从前端调用它,以JSON格式返回所有数据。
我很不确定在哪里以及如何编写查询,以便将它们传递到模式,然后Absince和Ecto处理其余的查询 你能做点什么吗
查询:
和在解析器中
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对象,则必须创建自定义标量并将其用作字段类型。 e、 g 然后
@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
```
如果我正确理解您的问题,您只需告诉Graphql您想要什么,它就会处理您需要的所有数据。如果需要过滤结果,可以将
arg
添加到字段中,在解析器函数中使用它。是的,这样我就可以手动执行。但是我如何将查询和突变封装到函数中,然后调用该函数,它将运行查询,无需通过GUI键入查询,即可编写api,然后编写函数并将要实现的逻辑放入其中,然后从前端调用该api。它将根据您编写的函数从数据库中获取记录,并在前端填充该记录。
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
```