Would this be as simple as defining your schema and def changeset and never writing any Repo.insert(changeset)?
It is possible and I find it as perfect way to validate API requests.
You can define your model without backend as:
defmodule MyApp.Models.File do
schema "" do
field :description, :string, virtual: true
field :url, :string, virtual: true
field :file_name, :string, virtual: true
field :ext, :string, virtual: true
field :mime, :string, virtual: true
field :size, :integer, virtual: true
end
def new_file_cs(model, params) do
model
|> cast(params, ~w(url file_name ext mime size), ~w(description))
end
end
and then somewhere call it as:
def handle_request(data) do
changeset = File.new_file_cs(%File{}, data)
case changeset.valid? do
true -> :ok
false -> {:error, changeset}
end
end
Such error response can be used with ChangesetView generated by phoenix to return uniform error response.
To summarize, your model should have empty schema "" and all fields should be virtual: true
There's an Ecto.Changeset like validation library called Justify. It allows you to validate against plain maps and structs. No schemas or types necessary.
https://github.com/sticksnleaves/justify
You can do stuff like:
import Justify
dataset =
%{email: "[email protected]"}
|> validate_required(:email)
|> validate_format(:email, ~r/\A\S@\S\z/)
dataset.valid? == true
Disclaimer: I made Justify
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With