Recommend patterns for enum runtime validation

Disclaimer: I’m still a beginner when it comes to Elixir data types, so my apologies if the question sounds “silly”

Is there a recommended pattern for enum runtime validation in Elixir? For instance, the function above receives an argument called “intent” which can be only the following string values: ["sso", "dsync", "audit_logs", "log_streams"]

Is it possible to avoid even calling the function if the intent is not supported? Not sure if pattern matching could be used for that case?

def generate_link(params, opts) when is_map_key(params, :organization) and is_map_key(params, :intent) do
  query = process_params(params, [:intent, :organization, :return_url, :success_url])
  post("/portal/generate_link", query, opts)
end
def generate_link(%{intent: intent, organisation: _} = params, opts) 
    when intent in ["sso", "dsync", "audit_logs", "log_streams"] do
  query = process_params(params, [:intent, :organization, :return_url, :success_url])
  post("/portal/generate_link", query, opts)
end

The list in the guard needs to be a compile time list.

You can use a module attribute, i.e. @intents ~w[sso dsync audit_logs log_streams] if it is used in multiple places, or create a guard (see defguard) if the guard is used in multiple places.

4 Likes

Edit: Too slow typing