Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Elixir changesets/validations without using models?

Would this be as simple as defining your schema and def changeset and never writing any Repo.insert(changeset)?

like image 320
Zac Avatar asked Oct 24 '25 14:10

Zac


2 Answers

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

like image 116
BurmajaM Avatar answered Oct 27 '25 11:10

BurmajaM


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

like image 35
anthonator Avatar answered Oct 27 '25 10:10

anthonator