【问题标题】:How to creating GraphQL queries from an Elixir API?如何从 Elixir API 创建 GraphQL 查询?
【发布时间】:2018-07-14 22:47:21
【问题描述】:

我有一个 Elixir API,可以使用 Graphiql 向我的数据库发送查询,如您所见,所有 crud 调用都运行良好。

field :users, list_of(:user) do
        resolve &Graphical.UserResolver.all/2
    end

这将返回数据库中的所有用户。现在显然,如果您使用前端,您不想手动输入查询,这并不理想。我将如何实现在架构文件中调用这些字段的函数?我该怎么写说这个查询

users{
  id,
  name,
  email
}

在 Elixir 本身中,以便我可以从前端调用它以返回 JSON 格式的所有数据。 我很不确定在哪里以及如何编写查询,以便将它们传递给模式,然后 Absinthe 和 Ecto 负责其余的工作。

【问题讨论】:

  • 如果我正确理解了您的问题,您只需告诉 Graphql 您想要什么,它就会处理您需要的所有数据。如果您需要过滤结果,您可以将arg 添加到您的字段中,在解析器函数中使用它。
  • 是的,所以我可以手动执行此操作。但是我如何将查询和突变封装到函数中,然后我可以调用该函数并运行查询,而无需通过 gui 输入查询
  • 写一个api,然后写一个函数,把你想要实现的逻辑放在里面,然后从前端调用那个api。它将根据你写的函数从数据库中获取记录并填充它在前端。

标签: elixir phoenix-framework graphql ecto


【解决方案1】:

可以做点什么 查询:

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

【讨论】:

    【解决方案2】:

    当您从 FE 查询 Absinthe 时,您将得到一个 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
        ```
    

    【讨论】:

      猜你喜欢
      • 2022-01-01
      • 2018-11-29
      • 2021-07-03
      • 2017-12-27
      • 2019-06-11
      • 1970-01-01
      • 2019-09-11
      • 2022-11-19
      • 2018-02-27
      相关资源
      最近更新 更多