How to create a enum with mime types?

Maybe my library could help you : SimpleEnum - Use Enumerations in Elixir.

The equivalent of your current implementation would be :

# my_app/types.ex
defmodule MyApp.Types do
  import SimpleEnum

  defenum :mime_type_enum,
    image_gif: "image/gif",
    image_png: "image/png",
    image_jpeg: "image/jpeg"
end

# my_app/schema.ex
import MyApp.Types

scalar :mime_type, name: "MimeType" do
  description("""
  Currently support mimetypes:\n
    - #{mime_type_enum(:__values__) |> Enum.join("\n  - ")}
  """)

  serialize(fn
    value when value in mime_type_enum(:__values__) -> value
    key when key in mime_type_enum(:__keys__) -> mime_type_enum(key, :value)
    _ -> :error
  end)

  parse(fn
    %Absinthe.Blueprint.Input.String{value: value} when value in mime_type_enum(:__values__) ->
      {:ok, mime_type_enum(value, :key)}

    _ ->
      :error
  end)
end

With this implementation :

  • Adding an Enum is very simple, you just have to add the values in the defenum/2
  • It will automatically update description and the serialize/1 and parse/1 functions of your scalar
  • Once the scalar is parsed, you can use the image_gif, image_png and image_jpeg atoms in Elixir for processing
2 Likes