-
-
Save shahryarjb/41464fcdfabc0d16aed2a1cbeb718c83 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 MishkaDatabase.CRUD do | |
defmacro __using__(opts) do | |
quote(bind_quoted: [opts: opts]) do | |
@interface_module opts | |
end | |
end | |
defmacro crud_edit(attr) do | |
quote do | |
module_selected = Keyword.get(@interface_module, :module) | |
error_atom = Keyword.get(@interface_module, :error_atom) | |
repo = Keyword.get(@interface_module, :repo) | |
Macro.escape(edit_record(unquote(attr), module_selected, error_atom, repo)) | |
end | |
end | |
def uuid(id) do | |
case Ecto.UUID.cast(id) do | |
{:ok, record_id} -> {:ok, :uuid, record_id} | |
_ -> {:error, :uuid} | |
end | |
end | |
def get_record_by_id(id, module, error_atom, repo) do | |
case repo.get(module, id) do | |
nil -> {:error, error_atom, :get_record_by_id} | |
record_info -> {:ok, error_atom, :get_record_by_id, record_info} | |
end | |
end | |
def edit_record(attrs, module, error_atom, repo) do | |
with {:ok, :uuid, record_id} <- uuid(attrs.id), | |
{:ok, error_atom, :get_record_by_id, record_info} <- get_record_by_id(record_id, module, error_atom, repo), | |
{:ok, info} <- update(record_info, attrs, module, repo) do | |
{:ok, error_atom, info} | |
else | |
{:error, :uuid} -> | |
{:error, error_atom, :uuid} | |
{:error, changeset} -> | |
{:error, error_atom, changeset} | |
_ -> | |
{:error, error_atom, :get_record_by_id} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment