Make a Lowercase Enum in Absinthe


Absinthe is an Elixir library that allows you to specify a graphql schema in Elixir. Here's how to make a lowercase enum in Absinthe.

By default an enum in Absinthe will be exposed as all-uppercase values. Here's the enum:

enum :salty_slug do
  value(:foaming)
  value(:nasty)
end

Then when queried:

query myQuery {
  someStuff {
    saltySlug
  }
}

The results look something like:

{
  /* ... */
  "someStuff": [
    {
      "saltySlug": "NASTY"
    },
    {
      "saltySlug": "FOAMING"
    },
  /* ... */
  ]
}

But those uppercase values sometimes look foamy nasty. So, let's make them lowercase. We adjust our enum definition, adding a name option on Enum.Value:

enum :salty_slug do
  value(:foaming, name: "foaming")
  value(:nasty, name: "nasty")
end

With the same query, the results will now be:

{
  /* ... */
  "someStuff": [
    {
      "saltySlug": "nasty"
    },
    {
      "saltySlug": "foaming"
    },
  /* ... */
  ]
}

Lowercase glory is attained. Ship it.

Optional: Underscore Sidequest

Another naming gotcha may be in play for you too: the valid characters allowed in an enum name.

We had dashes in our data. We wanted it to match in the enum, so we tried something like this:

enum :salty_slug do
  value(:foaming, name: "foaming")
  value(:nasty, name: "super-nasty")
end

But it didn't work, erroring with:

Enum value name "super-nasty" has invalid characters.

Name does not match possible ~r/^[_A-Za-z][_0-9A-Za-z]*$/ regex.

Turns out that the only separator allowed was underscores, so we were stuck with super_nasty:

enum :salty_slug do
  value(:foaming, name: "foaming")
  value(:nasty, name: "super_nasty")
end

Are underscores super nasty? Not really. And at least they're valid enum names.