Created
October 24, 2022 08:51
-
-
Save hl/e40ed5a9965e111a8800c3a36cc399ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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