Created
February 12, 2025 13:34
-
-
Save joeljuca/bf3c0a19e4a880a9513dc8f324ab5df7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# I wont use it anymore, but it sounded like a nice way to | |
# validate map fields with a dedicated schema | |
defmodule M do | |
@spec validate_meta(changeset :: Ecto.Changeset.t()) :: | |
Ecto.Changeset.t() | |
defp validate_meta(%Ecto.Changeset{valid?: false} = changeset), do: changeset | |
defp validate_meta(changeset) do | |
params = changeset |> get_change(:meta) | |
schema = %{ | |
upload_id: :string, | |
asset_id: :string, | |
playback_id: :string, | |
title: :string | |
} | |
changeset_meta = | |
{%{}, schema} | |
|> cast(params, Map.keys(schema)) | |
|> validate_required([:upload_id]) | |
with {:ok, _} <- apply_action(changeset_meta, :validate_meta) do | |
changeset | |
else | |
{:error, %Ecto.Changeset{} = changeset_meta} -> | |
changeset_meta.errors | |
|> Enum.reduce(changeset, fn {field, {msg, meta}}, changeset -> | |
changeset |> add_error(:meta, "#{field} #{msg}", meta) | |
end) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment