Skip to content

Instantly share code, notes, and snippets.

@shahryarjb
Created January 12, 2021 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shahryarjb/41464fcdfabc0d16aed2a1cbeb718c83 to your computer and use it in GitHub Desktop.
Save shahryarjb/41464fcdfabc0d16aed2a1cbeb718c83 to your computer and use it in GitHub Desktop.
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