2023-01-24 16:42:11 +13:00
# Use Enums with GraphQL
2021-03-29 08:46:23 +13:00
2024-04-02 08:29:19 +13:00
If you define an `Ash.Type.Enum` , that enum type can be used both in attributes _and_ arguments. You will need to add `graphql_type/0` to your implementation. AshGraphql will ensure that a single type is defined for it, which will be reused across all occurrences. If an enum
2021-04-24 10:44:56 +12:00
type is referenced, but does not have `graphql_type/0` defined, it will
be treated as a string input.
For example:
```elixir
defmodule AshPostgres.Test.Types.Status do
@moduledoc false
use Ash.Type.Enum, values: [:open, :closed]
def graphql_type, do: :ticket_status
2023-05-24 09:11:58 +12:00
# Optionally, remap the names used in GraphQL, for instance if you have a value like `:"10"`
# that value is not compatible with GraphQL
def graphql_rename_value(:"10"), do: :ten
def graphql_rename_value(value), do: value
2024-03-26 16:43:59 +13:00
# You can also provide descriptions for the enum values, which will be exposed in the GraphQL
# schema.
# Remember to have a fallback clause that returns nil if you don't provide descriptions for all
# values.
def graphql_describe_enum_value(:open), do: "The post is open"
def graphql_describe_enum_value(_), do: nil
2021-04-24 10:44:56 +12:00
end
```
### Using custom absinthe types
2021-03-29 08:46:23 +13:00
You can implement a custom enum by first adding the enum type to your absinthe schema (more [here ](https://hexdocs.pm/absinthe/Absinthe.Type.Enum.html )). Then you can define a custom Ash type that refers to that absinthe enum type.
```elixir
# In your absinthe schema:
enum :status do
value(:open, description: "The post is open")
value(:closed, description: "The post is closed")
end
```
```elixir
2023-05-24 09:11:58 +12:00
# Your custom Ash Type
2021-03-29 08:46:23 +13:00
defmodule AshGraphql.Test.Status do
2024-04-25 01:21:26 +12:00
use Ash.Type.Enum, values: [:open, :closed]
2021-03-29 08:46:23 +13:00
2024-04-25 01:21:26 +12:00
use AshGraphql.Type
2021-03-29 08:46:23 +13:00
@impl true
2024-04-25 01:21:26 +12:00
# tell Ash not to define the type for that enum
def graphql_define_type?(_), do: false
2021-03-29 08:46:23 +13:00
end
```