From e388192851cbdc8bb08561ab0e211e8390d15ada Mon Sep 17 00:00:00 2001 From: Danielwhyte Date: Wed, 24 Oct 2018 12:22:25 +0100 Subject: [PATCH] raises error if required fields are missing, #5 --- lib/alog.ex | 28 ++++++++++++++++++++++ test/alog_test.exs | 60 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) diff --git a/lib/alog.ex b/lib/alog.ex index 1fe6210..b6e456a 100644 --- a/lib/alog.ex +++ b/lib/alog.ex @@ -30,6 +30,12 @@ defmodule Alog do Alog expects your `Repo` to belong to the same base module as the schema. So if your schema is `MyApp.User`, or `MyApp.Accounts.User`, your Repo should be `MyApp.Repo`. + + Any schema that uses Alog must include the fields `:deleted` of type `:boolean` and default false, + and `:entry_id` of type `:string`. + + field(:deleted, :boolean, default: false) + field(:entry_id, :string) """ @callback insert(struct) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} @@ -53,6 +59,28 @@ defmodule Alog do @repo __MODULE__ |> Module.split() |> List.first() |> Module.concat("Repo") + if not Map.has_key?(%__MODULE__{}, :deleted) || not is_boolean(%__MODULE__{}.deleted) do + raise """ + + Your Schema must have a key :deleted, with type :boolean and default false. + + Add the following line to your schema: + + field(:deleted, :boolean, default: false) + """ + end + + if not Map.has_key?(%__MODULE__{}, :entry_id) do + raise """ + + Your Schema must have a key :entry_id, with type :string + + Add the following line to your schema: + + field(:entry_id, :string) + """ + end + @doc """ Applies a schema's changeset function and inserts it into the database. Adds an entry id to link it to future updates of the item. diff --git a/test/alog_test.exs b/test/alog_test.exs index 6b9d05d..1469150 100644 --- a/test/alog_test.exs +++ b/test/alog_test.exs @@ -83,4 +83,64 @@ defmodule AlogTest do assert length(User.all()) == 0 end end + + describe "required fields" do + test "schema without delete field raises error" do + assert_raise RuntimeError, fn -> + defmodule BadSchema do + use Ecto.Schema + use Alog + + schema "bad_schema" do + field(:entry_id, :string) + timestamps() + end + end + end + end + + test "schema without entry_id field raises error" do + assert_raise RuntimeError, fn -> + defmodule BadSchema do + use Ecto.Schema + use Alog + + schema "bad_schema" do + field(:deleted, :boolean, default: false) + timestamps() + end + end + end + end + + test "schema with deleted field of wrong type raises error" do + assert_raise RuntimeError, fn -> + defmodule BadSchema do + use Ecto.Schema + use Alog + + schema "bad_schema" do + field(:entry_id, :string) + field(:deleted, :string) + timestamps() + end + end + end + end + + test "both required fields do not raise error" do + assert (fn -> + defmodule BadSchema do + use Ecto.Schema + use Alog + + schema "bad_schema" do + field(:entry_id, :string) + field(:deleted, :boolean, default: false) + timestamps() + end + end + end).() + end + end end