GraphQL adapter for Yggdrasil
This project is a GraphQL adapter for Yggdrasil publisher/subscriber.
Small example
Let's say we want to have the following GraphQL subscription:
subscription {
events(channel: "my_channel") {
content
}
}
And we have a process in Elixir that, using Yggdrasil, generates the
following event:
Yggdrasil.publish(
%Yggdrasil.Channel{name: "my_channel"},
%{content: "some message"}
)Using Absinthe, our Schema would look like this:
defmodule MyAppWeb.Schema do
use Absinthe.Schema
object :message do
field :content, :string
end
query do
end
subscription do
field :events, :message do
arg :channel, non_null(:string)
config fn args, %{context: %{pubsub: endpoint}} ->
channel = %Yggdrasil.Channel{name: args.channel}
Yggdrasil.GraphQL.subscribe(endpoint, :events, channel)
end
end
end
endPhoenix setup
This is an extract from this guide modified slightly to fit this example.
-
Add the
Absinthelibraries:{:absinthe, "~> 1.4"}, {:absinthe_phoenix, "~> 1.4"}, -
Add the
Phoenix.PubSubconfiguration for your endpoint:config :my_app, MyAppWeb.Endpoint, # ... other config pubsub: [ name: MyApp.PubSub, adapter: Phoenix.PubSub.PG2 ] -
In your application supervisor, add a line after your existing endpoint
supervision line:
Where[ # other children ... supervisor(MyAppWeb.Endpoint, []), # this line should already exist. supervisor(Absinthe.Subscription, [MyAppWeb.Endpoint]), # add this line # other children ... ]MyAppWeb.Endpointis the name of your application’s phoenix endpoint. -
In your
MyAppWeb.Endpointmodule add:use Absinthe.Phoenix.Endpoint -
In your socket add:
- Phoenix 1.3
use Absinthe.Phoenix.Socket, schema: MyAppWeb.Schema - Phoenix 1.2
use Absinthe.Phoenix.Socket def connect(_params, socket) do socket = Absinthe.Phoenix.Socket.put_schema(socket, MyAppWeb.Schema) {:ok, socket} end
- Phoenix 1.3
And that should be enough to have a working subscription setup.
GraphQL adapter
The GraphQL adapter has the following rules:
-
The
adaptername is identified by the atom:graphql. -
The channel
namemust be a tuple with theendpointname, the subscriptionfieldand anYggdrasilchannel to any of the available adapters. -
The
transformermust encode to a map. It is recommended to leave the encoding and decoding to the underlying adapter. Defaults to:defaulttransformer. -
The
backendis and always should be:graphql.
The function Yggdrasil.GraphQL.subscribe/3 is in charged of creating the
channel and generating the topic forAbsinthe.
Installation
Using this GraphQL adapter with Yggdrasil is a matter of adding the available
hex package to your mix.exs file e.g:
def deps do
[{:yggdrasil_graphql, "~> 0.1"}]
endRelevant projects used
- Absinthe: GraphQL toolkit for Elixir
Author
Alexander de Sousa.
License
yggdrasil_graphql is released under the MIT License. See the LICENSE file for
further details.