belgoros

belgoros

Optional GraphQL argument raises no function clause matching in Decimal.to_string/2

I decided to change from :float to :decimal types in an Phoenix App. And there is a weird case where I post the below mutation:

@desc "Create a wallet"
    field :create_wallet, :wallet do
      arg(:currency, non_null(:currency_type))
      arg(:user_id, non_null(:id))
      arg(:units, :decimal)

      resolve(&Resolvers.WalletResolver.create_wallet/3)
    end

without putting a value for units argument. This raises the error pointing to the Decimal library:

POST /api/graphiql
[debug] Processing with Absinthe.Plug.GraphiQL
  Parameters: %{"query" => "mutation {\n  createWallet(currency: CAD, userId: 1) {\n    id\n    currency\n    units\n    user {\n      id\n      email\n      name\n    }\n  }\n}", "variables" => nil}
  Pipelines: [:api]
[debug] ABSINTHE schema=PaymentServerWeb.Schema variables=%{}
---
mutation {
  createWallet(currency: CAD, userId: 1) {
    id
    currency
    units
    user {
      id
      email
      name
    }
  }
}
---
[debug] QUERY OK source="wallets" db=1.6ms queue=1.1ms idle=1784.6ms
INSERT INTO "wallets" ("currency","user_id","units","inserted_at","updated_at") VALUES ($1,$2,$3,$4,$5) RETURNING "id" [:CAD, 1, 0.0, ~N[2024-04-10 13:43:10], ~N[2024-04-10 13:43:10]]
↳ PaymentServerWeb.Graphql.Resolvers.WalletResolver.create_wallet/3, at: lib/payment_server_web/resolvers/wallet_resolver.ex:23
[debug] QUERY OK source="users" db=1.4ms idle=1790.7ms
SELECT u0."id", u0."email", u0."name", u0."inserted_at", u0."updated_at", u0."id" FROM "users" AS u0 WHERE (u0."id" = $1) [1]
↳ Dataloader.Source.Dataloader.Ecto.run_batch/2, at: lib/dataloader/ecto.ex:703
[info] Sent 500 in 86ms
[error] #PID<0.494.0> running Phoenix.Endpoint.SyncCodeReloadPlug (connection #PID<0.478.0>, stream id 2) terminated
Server: localhost:4000 (http)
Request: POST /api/graphiql
** (exit) an exception was raised:
    ** (FunctionClauseError) no function clause matching in Decimal.to_string/2
        (decimal 2.1.1) lib/decimal.ex:1362: Decimal.to_string(0.0, :scientific)
        (absinthe 1.7.6) lib/absinthe/phase/document/result.ex:55: Absinthe.Phase.Document.Result.data/2
        (absinthe 1.7.6) lib/absinthe/phase/document/result.ex:104: Absinthe.Phase.Document.Result.field_data/3
        (absinthe 1.7.6) lib/absinthe/phase/document/result.ex:22: Absinthe.Phase.Document.Result.process/2
        (absinthe 1.7.6) lib/absinthe/phase/document/result.ex:11: Absinthe.Phase.Document.Result.run/2
...

Moreover, the wallet was created successfully with the default units value set to 0.0.

If I pass is the value for unitsin the GraphQL mutation above, it works without error:

debug] Processing with Absinthe.Plug.GraphiQL
  Parameters: %{"query" => "mutation {\n  createWallet(currency: GBP, userId: 1, units: 30.21) {\n    id\n    currency\n    units\n    user {\n      id\n      email\n      name\n    }\n  }\n}", "variables" => nil}
  Pipelines: [:api]
[debug] ABSINTHE schema=PaymentServerWeb.Schema variables=%{}
---
mutation {
  createWallet(currency: GBP, userId: 1, units: 30.21) {
    id
    currency
    units
    user {
      id
      email
      name
    }
  }
}
---
[debug] QUERY OK source="wallets" db=2.7ms idle=1577.6ms
INSERT INTO "wallets" ("currency","user_id","units","inserted_at","updated_at") VALUES ($1,$2,$3,$4,$5) RETURNING "id" [:GBP, 1, Decimal.new("30.21"), ~N[2024-04-10 13:51:15], ~N[2024-04-10 13:51:15]]
↳ PaymentServerWeb.Graphql.Resolvers.WalletResolver.create_wallet/3, at: lib/payment_server_web/resolvers/wallet_resolver.ex:23
[debug] QUERY OK source="users" db=1.3ms idle=1583.3ms
SELECT u0."id", u0."email", u0."name", u0."inserted_at", u0."updated_at", u0."id" FROM "users" AS u0 WHERE (u0."id" = $1) [1]

A simple test proves it as well:

...
@create_wallet_mutation """
  mutation ($currency: CurrencyType!, $userId: ID!, $units: Decimal) {
    createWallet(currency: $currency, userId: $userId, units: $units) {
      currency
      units
      user {
        id
        email
      }
    }
  }
  """
...
test "it should create a new Wallet with valid attributes", %{conn: _conn} do
    user = insert(:user)

    wallet_input = %{
      "currency" => "GBP",
      "userId" => user.id,
      "units" => 0 # remove this argument and the test will fail!
    }

    {:ok, ref} =
      Absinthe.run(@create_wallet_mutation, PaymentServerWeb.Schema, variables: wallet_input)

    expected = %{
      data: %{
        "createWallet" => get_in(ref, [:data, "createWallet"])
      }
    }

    assert ref == expected
  end

Any ideas?

Marked As Solved

belgoros

belgoros

I had to add default_value: 0.0 to the mutation definition:

@desc "Create a wallet"
    field :create_wallet, :wallet do
      arg(:currency, non_null(:currency_type))
      arg(:user_id, non_null(:id))
      arg(:units, :decimal, default_value: 0.0)

      resolve(&Resolvers.WalletResolver.create_wallet/3)
    end

Where Next?

Popular in Questions Top

Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
Kagamiiiii
Student &amp; New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New

Other popular topics Top

belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement