refactor: extract helper modules to remove code duplication
This commit is contained in:
parent
36776f8e28
commit
9af7381843
3 changed files with 163 additions and 0 deletions
55
lib/mv/membership/helpers/visibility_config.ex
Normal file
55
lib/mv/membership/helpers/visibility_config.ex
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
defmodule Mv.Membership.Helpers.VisibilityConfig do
|
||||
@moduledoc """
|
||||
Helper functions for normalizing member field visibility configuration.
|
||||
|
||||
Handles conversion between string keys (from JSONB) and atom keys (Elixir convention).
|
||||
JSONB in PostgreSQL converts atom keys to string keys when storing.
|
||||
This module provides functions to normalize these back to atoms for Elixir usage.
|
||||
"""
|
||||
|
||||
@doc """
|
||||
Normalizes visibility config map keys from strings to atoms.
|
||||
|
||||
JSONB in PostgreSQL converts atom keys to string keys when storing.
|
||||
This function converts them back to atoms for Elixir usage.
|
||||
|
||||
## Parameters
|
||||
|
||||
- `config` - A map with either string or atom keys
|
||||
|
||||
## Returns
|
||||
|
||||
A map with atom keys (where possible)
|
||||
|
||||
## Examples
|
||||
|
||||
iex> normalize(%{"first_name" => true, "email" => false})
|
||||
%{first_name: true, email: false}
|
||||
|
||||
iex> normalize(%{first_name: true, email: false})
|
||||
%{first_name: true, email: false}
|
||||
|
||||
iex> normalize(%{"invalid_field" => true})
|
||||
%{}
|
||||
"""
|
||||
@spec normalize(map()) :: map()
|
||||
def normalize(config) when is_map(config) do
|
||||
Enum.reduce(config, %{}, fn
|
||||
{key, value}, acc when is_atom(key) ->
|
||||
Map.put(acc, key, value)
|
||||
|
||||
{key, value}, acc when is_binary(key) ->
|
||||
try do
|
||||
atom_key = String.to_existing_atom(key)
|
||||
Map.put(acc, atom_key, value)
|
||||
rescue
|
||||
ArgumentError -> acc
|
||||
end
|
||||
|
||||
_, acc ->
|
||||
acc
|
||||
end)
|
||||
end
|
||||
|
||||
def normalize(_), do: %{}
|
||||
end
|
||||
Loading…
Add table
Add a link
Reference in a new issue