links: [[Phoenix MOC]] --- # Add Absinthe to Phoenix app ### Installation Add these plugins to the phoenix app ```exs {:absinthe, "~> 1.6"}, {:absinthe_plug, "~> 1.5"} ``` ### Schema Each graphql query or mutation has two parts, schema and resolver. **Schema** defines how the data is and *resolver* finds the data in backend and returns to frontend Now create a schema directory in the **web** folder and a **schema** file so we can start writing schema ```ex defmodule KancheWeb.Schema do use Absinthe.Schema query do @desc "Get all users" field :users, list_of(:user) do resolve &KancheWeb.Resolvers.Accounts.users/3 end end object :user do field :id, non_null(:id) field :email, non_null(:string) field :password_hash, non_null(:string) end end ``` In the above example, we instruct to use *Absinthe.Schema* and we have a *query macro* where we define the queries with *description*, *field* and *resolve*. The *object* macro can be used to defined **user** object containing three fields ### Resolver Create a new **resolver** directory under web and then create a elixir file with context name *Context.ex*, in this example *Accounts.ex* ```ex defmodule KancheWeb.Resolvers.Accounts do alias Kanche.Accounts def users(_, _, _) do {:ok, Accounts.list_users()} end end ``` Resolvers are 3-arity functions. Most of the time you care about the second argument which is a map of query arguments. The resolver functions simply delegate the work to the generated **Accounts** context module and return an **:ok** tuple The only thing left is to configure **router.ex** file ```ex scope "/graphql" do pipe_through :api # Absinthe Graphql Routes forward "/graphiql", Absinthe.Plug.GraphiQL, schema: KancheWeb.Schema, interface: :simple forward "/", Absinthe.Plug, schema: KancheWeb.Schema end ``` That's it 🥳 --- tags: #graphql, #phoenix, #absinthe, #basics sources: - [https://pragmaticstudio.com/tutorials/how-to-setup-graphql-in-a-phoenix-app](How to setup graphql in a phoenix app) - [https://www.howtographql.com/graphql-elixir/2-queries/](How to graphql)