Skip to content

Instantly share code, notes, and snippets.

@hl
Created October 24, 2022 08:51
Show Gist options
  • Save hl/e40ed5a9965e111a8800c3a36cc399ff to your computer and use it in GitHub Desktop.
Save hl/e40ed5a9965e111a8800c3a36cc399ff to your computer and use it in GitHub Desktop.
defmodule Normalize do
import Ecto.Changeset
@spec normalize(map(), Keyword.t()) :: {:ok, map()} | {:error, Ecto.Changeset.t()}
def normalize(params, input_schema) do
types =
Map.new(input_schema, fn {field, opts} ->
{field, List.first(opts)}
end)
changeset =
for {field, opts} <- input_schema,
opt <- opts,
reduce: cast({%{}, types}, params, Map.keys(types)) do
changeset ->
case opt do
{:required, true} -> validate_required(changeset, field)
_opt -> changeset
end
end
apply_action(changeset, :insert)
end
end
input_schema = [
title: [:string, required: true],
slug: [:string]
]
params = %{"title" => "Hello", "slug" => "hello", "world" => "hello"}
Normalize.normalize(params, input_schema)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment