cclark

cclark

How to use Enum and Custom Scalars together in Absinthe?

I’m new to Elixir, Phoenix and Absinthe but trying to write an API onto an existing dataset. The dataset includes information about trails and they have a status attribute with values of 1, 2, 3 or 4. In the domain these map to Green (1), Yellow(2), Amber(3) and Red(4) so I’d like to use the actual enum values as it would be much more expressive.

For the GraphQL API onto this it would be much nicer if I could write a query like:


query {

  trails(havingStatus: RED) {

    id

    name

    status

  }

}

In my schema I’ve defined an enum as


 @desc "Current status of the trail"

  enum :trail_status do

    value :green, as: 1, description: "Green: Clear"

    value :yellow, as: 2, description: "Yellow: Minor Issue"

    value :amber, as: 3, description: "Amber: Significant Issue"

    value :red, as: 4, description: "Red: Major Issue"

  end

This allows me to query and enforce that the user chooses valid values for havingStatus. However, in my results I see the raw value of


      {

        "status": 4,

        "name": "Lost Loop",

        "id": "16601"

      }

where I’d really like to have the 3 be returned as RED.

First does this make sense to do? If the client already knows about GREEN, YELLOW, AMBER and RED when making the query then it seems like a failure to make the client know how to receive 1-4 and map it to those values.

It seems like a custom scalar might be one way to get at this. All of the examples I can find are for dates and make sense. But when I have a very specific enumeration of four values I wonder if that is overkill and it seems like I’d lose the nice ability to introspect and see the only valid values. So I think I want a combination of an enum and a custom scalar type?

Any thoughts or pointers to Absinthe/GraphQL articles on the subject would be greatly appreciated.

Most Liked

kokolegorille

kokolegorille

Hello, welcome to the forum.

I use simple atoms, without as when I don’t need to use db, like so

  enum :sort_order do
    value :asc
    value :asc_nulls_last
    value :asc_nulls_first
    value :desc
    value :desc_nulls_last
    value :desc_nulls_first
  end

But if You want to persists Int in the DB and keep nice looking status, I would use a scalar. Nothing really complicate, You just need a parse and a serialize functions.

I use this for json.

  scalar :json do
    parse fn input ->
      case Jason.decode(input.value) do
        {:ok, result} -> result
        _ -> :error
      end
    end
    serialize &Jason.encode!/1
  end

And with your Enum requirement, it would be simple to write those 2 functions. For example…

scalar :status do
  parse fn 1 -> :green; 2 -> :yellow; 3 -> :amber; 4 -> :red; _ -> :error end
  serialize fn :green -> 1; :yellow -> 2; :amber -> 3; :red -> 4; _ -> :error end
end
StefanL

StefanL

You might want to have a look at EctoEnum, it will probably provide the casting from/to integers in ecto that you are searching for.

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
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
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
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
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New

Other popular topics Top

Tee
can someone please explain to me how Enum.reduce works with maps
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
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
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
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
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
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
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement