Search code examples
elixirphoenix-frameworkgraphqlecto

How to creating GraphQL queries from an Elixir API?


I have an Elixir API that can use Graphiql to send queries to my database, all the crud calls are working fine as you can see.

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

this returns all the users from a database. Now obviously this isn't ideal if your using a front end, you don't want to manually type out the query. How would i go about implementing functions that call these fields in the schema file? How do I write say this query

users{
  id,
  name,
  email
}

in the Elixir itself, so that I can call it from a front end to return all the data in JSON format. I am quite unsure where and how to write the queries so that they are passed to the schema and then Absinthe and Ecto take care of the rest.


Solution

  • Can do something Query:

    users(scope: "some"){}
    

    And in the resolver

    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