Git Product home page Git Product logo

absinthe_client's Introduction

AbsintheClient

CI Docs Hex pm

A GraphQL client designed for Elixir Absinthe.

Features

  • Performs query and mutation operations via JSON POST requests.

  • Performs subscription operations over WebSockets (Absinthe Phoenix).

  • Automatically re-establishes subscriptions on socket disconnect/reconnect.

  • Supports virtually all Req.request/1 options, notably:

    • Bearer authentication (via the auth step).

    • Retries on errors (via the retry step).

Usage

The fastest way to use AbsintheClient is with Mix.install/2 (requires Elixir v1.12+):

Mix.install([
  {:absinthe_client, "~> 0.1.0"}
])

Req.new(base_url: "https://rickandmortyapi.com")
|> AbsintheClient.attach()
|> Req.post!(graphql: "query { character(id: 1) { name } }").body
#=> %{"data" => "character" => %{"name" => "Rick Sanchez"}}}

If you want to use AbsintheClient in a Mix project, you can add the above dependency to your list of dependencies in mix.exs.

AbsintheClient is intended to be used by building a common client struct with a base_url and re-using it on each operation:

base_url = "https://rickandmortyapi.com"
req = Req.new(base_url: base_url) |> AbsintheClient.attach()

Req.post!(req, graphql: "query { character(id: 2) { name } }").body
#=> %{"data" => "character" => %{"name" => "Morty Smith"}}}

Refer to AbsintheClient for more information on available options.

Subscriptions (WebSockets)

AbsintheClient supports WebSocket operations via a custom Req adapter. You must first start the WebSocket connection, then you make the request with Req.request/2:

base_url = "https://my-absinthe-server"
req = Req.new(base_url: base_url) |> AbsintheClient.attach()

ws = AbsintheClient.WebSocket.connect!(req, url: "/socket/websocket")

Req.request!(req, web_socket: ws, graphql: "subscription ...").body
#=> %AbsintheClient.WebSocket.Subscription{}

Note that although AbsintheClient can use the :web_socket option to execute all GraphQL operation types, in most cases it should continue to use HTTP for queries and mutations. This is because queries and mutations do not require a stateful or long-lived connection and depending on the number of concurrent requests it may be more efficient to avoid blocking the socket for those operations.

Refer to AbsintheClient.attach/2 for more information on handling subscriptions.

Authentication

AbsintheClient supports Bearer authentication for HTTP and WebSocket operations:

base_url = "https://my-absinthe-server"
auth = {:bearer, "token"}
req = Req.new(base_url: base_url, auth: auth) |> AbsintheClient.attach()

# ?Authentication=Bearer+token will be sent on the connect request.
ws = AbsintheClient.WebSocket.connect(req, url: "/socket/websocket")

If you use your client to authenticate then you can set :auth by merging options:

base_url = "https://my-absinthe-server"
req = Req.new(base_url: base_url) |> AbsintheClient.attach()

doc = "mutation { login($input) { token } }"
graphql = {doc, %{user: "root", password: ""}}
token = Req.post!(req, graphql: graphql).body["data"]["login"]["token"]
req = Req.Request.merge_options(req, auth: {:bearer, token})

Why AbsintheClient?

There is another popular GraphQL library for Elixir called Neuron. So why choose AbsintheClient? In short, you might use AbsintheClient if you need Absinthe Phoenix subscription support, if you want to avoid global configuration, and if you want to declaratively build your requests. For comparison:

AbsintheClient Neuron
HTTP Req, Finch HTTPoison, hackney
WebSockets Slipstream, Mint.WebSocket n/a
Configuration %Req.Request{} Application and Process-based
Request style Declarative, builds a struct Imperative, invokes a function

Acknowledgements

AbsintheClient is built on top of the Req requests library for HTTP and the Slipstream WebSocket library for Phoenix Channels.

License

MIT license. Copyright (c) 2019 Michael A. Crumm Jr., Ben Wilson

absinthe_client's People

Contributors

benwilson512 avatar fastjames avatar mcrumm avatar oliphaunte avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

absinthe_client's Issues

Demo code yields FunctionClauseError

@mcrumm I copied the usage code from the README into an iex session and got the following error

** (FunctionClauseError) no function clause matching in URI.parse/1

    The following arguments were given to URI.parse/1:

        # 1
        [graphql: "query { character(id: 1) { name } }"]

    Attempted function clauses (showing 2 out of 2):

        def parse(%URI{} = uri)
        def parse(string) when is_binary(string)

    (elixir 1.13.4) lib/uri.ex:765: URI.parse/1
    (req 0.3.6) lib/req.ex:423: Req.post/2
    (req 0.3.6) lib/req.ex:328: Req.post!/2

I ran:

Mix.install([
  {:absinthe_client, "~> 0.1.0"}
])

Req.new(base_url: "https://rickandmortyapi.com")
|> AbsintheClient.attach()
|> Req.post!(graphql: "query { character(id: 1) { name } }").body

Any idea what I'm doing wrong? I see that the output from AbsintheClient.attach() has a call to URI.parse with an empty string:

%Req.Request{
  method: :get,
  url: URI.parse(""),
  headers: [],
  body: nil,
  options: %{base_url: "https://rickandmortyapi.com"},
  registered_options: #MapSet<[:unix_socket, :params, :path_params, :async,
   :cache_dir, :base_url, :raw, :connect_options, :json, :connect_params,
   :user_agent, :max_retries, :auth, :pool_timeout, :location_trusted, :finch,
   :plug, :output, :compress_body, :receive_timeout, :finch_request,
   :compressed, :max_redirects, :web_socket, :range, :cache, :extract, :form,
   :retry_log_level, :follow_redirects, :retry_delay, :graphql, :decode_body,
   :http_errors, :retry]>,
  halted: false,
  adapter: &Req.Steps.run_finch/1,
  request_steps: [
    graphql_run: #Function<0.34809413/1 in AbsintheClient."-fun.run/1-">,
    put_user_agent: &Req.Steps.put_user_agent/1,
    compressed: &Req.Steps.compressed/1,
    encode_body: &Req.Steps.encode_body/1,
    put_base_url: &Req.Steps.put_base_url/1,
    auth: &Req.Steps.auth/1,
    put_params: &Req.Steps.put_params/1,
    put_path_params: &Req.Steps.put_path_params/1,
    put_range: &Req.Steps.put_range/1,
    cache: &Req.Steps.cache/1,
    put_plug: &Req.Steps.put_plug/1,
    compress_body: &Req.Steps.compress_body/1
  ],
  response_steps: [
    retry: &Req.Steps.retry/1,
    follow_redirects: &Req.Steps.follow_redirects/1,
    decompress_body: &Req.Steps.decompress_body/1,
    decode_body: &Req.Steps.decode_body/1,
    handle_http_errors: &Req.Steps.handle_http_errors/1,
    output: &Req.Steps.output/1
  ],
  error_steps: [retry: &Req.Steps.retry/1],
  private: %{}
}

Release 0.1.1 on Hex

Hey @benwilson512, it seems like you bumped the version to 0.1.1 but that version isn't on Hex. Would you mind releasing it there as well, please? Thank you!

Support for Codegen

Thanks a lot for absinthe_client. We've been waiting for it for a long time.
One of the main issue with consuming any graphql api(our or 3rd party) is it can change.
We can use different codegen libraries to ensure that the code that we are using is not out of date in js/ts world.
We have artem in elixir world.

Would a codegen be within the scope of this project ? If yes, it would be quality of life addition ๐Ÿ˜Š.
This can be very handy tool when our whole ui is just live_view and have almost zero js/ts.

Thanks again for open-sourcing absinthe_client.

tag update needed

Because the lock depends on swoosh 1.14.2 which depends on req ~> 0.4 or ~> 1.0, the lock requires req ~> 0.4 or ~> 1.0.
And because every version of absinthe_client depends on req ~> 0.3.0, the lock is incompatible with absinthe_client.
And because your app depends on the lock, no version of absinthe_client is allowed.
So, because your app depends on absinthe_client ~> 0.1.0, version solving failed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.