Snippets Collections
defmodule GraphQL.GraphqlSchema do
  use Absinthe.Schema

  alias GraphQL.Book

  @desc "A Book"
  object :book do
    field :id, :integer
    field :name, :string
    field :author, :string

  end

# Example fake data
@book_information %{
  "book1" => %{id: 1, name: "Harry Potter", author: "JK Rowling"},
  "book2" => %{id: 2, name: "Charlie Factory", author: "Bernard"},
  "book3" => %{id: 3, name: "Sherlock Holmes", author: "Sheikhu"}
}

@desc "hello world"
query do
 import_fields(:book_queries)
end

object :book_queries do
  field :book_info, :book do
    arg :id, non_null(:id)
    resolve fn %{id: book_id}, _ ->
      {:ok, @book_information[book_id]}
    end
  end

  field :get_book, :book do
    arg(:id, non_null(:id))
    resolve fn %{id: bookId}, _ ->
      {:ok, Book.get_info!(bookId)}
    end
  end

  field :get_all_books, non_null(list_of(non_null(:book))) do
    resolve fn _, _, _ ->
      {:ok, Book.list_information()}
    end
  end
end

mutation do
  import_fields(:mutations)
end

object :mutations do
  field :create_book, :book do
    arg(:name, non_null(:string))
    arg(:author, non_null(:string))
    resolve fn args, _ ->
       Book.create_info(args)
    end
  end
end
end

# mix.ex
{:absinthe, "~> 1.7"},
{:absinthe_plug, "~> 1.5"},
{:cors_plug, "~> 3.0"}

# For that go to endpoint.ex file. In the file right above plug MyBlogApiWeb.Router add this line plug CORSPlug, origin:"*". The option origin means, what origin we should allow traffic from.
# Adding "*" means we are allowing traffic from everywhere. If we want to be specific for our ember application. We can add origin: "localhost:4200".
plug CORSPlug, origin: "*"
plug CORSPlug, origin: ~r/^https?:\/\/localhost:\d{4}$/

# router.ex

scope "/api", GraphQLWeb do
  pipe_through :api
  forward("/", Absinthe.Plug, schema: GraphQL.Grapha)
end

scope "/" do
  forward "/GraphiQL", Absinthe.Plug.GraphiQL, schema: GraphQL.Grapha
end

# Or endpoint.ex

plug Absinthe.Plug.GraphiQL, schema: App.GraphQL.Schema
  @impl Plug.ErrorHandler
  def handle_errors(conn, %{
        kind: _kind,
        reason: %ArgumentError{
          message: message
        },
        stack: _stack
      }) do
    conn
    |> put_status(:bad_request)
    |> json(%{error: message})
  end

  def handle_errors(conn, %{kind: _kind, reason: _reason, stack: _stack}) do
    json(conn, %{error: "Something went wrong"})
  end
MIX_ENV=prod WEBPACK_ENV=prod PORT=4001 mix phx.server
just webpack-dev-watch
star

Wed Dec 20 2023 16:10:02 GMT+0000 (Coordinated Universal Time)

#elixir
star

Sat Mar 05 2022 13:25:19 GMT+0000 (Coordinated Universal Time)

#elixir
star

Wed Mar 10 2021 07:01:46 GMT+0000 (Coordinated Universal Time)

#elixir

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension