Building small elixir services using Ecto (without Phoenix)

mix archive.install mix_templates
mix archive.install mix_generator
mix template.install hex gen_template_ecto_service
mix gen ecto_service namely
mix deps.get
git init
git add .
git commit -m "Initial commit from ecto_service"
git remote add origin git@github.com:aforward/namely.git
git push -u origin master
mix ecto.reset
iex -S mix
iex(0)> Action.add("name_added", "Name", "invoice")
%Action{} |>
Action.changeset(%{name: "alias_added", entity_type: "Name", entity_id: "invoice", data: %{alias: "bill"}}) |>
Repo.insert
10:15 ~/project/namely (master)$ psql namely_dev
psql (9.6.2)
Type "help" for help.namely_dev=#
namely_dev=# select * from actions;
id |    name     | entity_type | entity_id |       data
----+-------------+-------------+-----------+-------------------
1 | name_added | Name | invoice |
2 | alias_added | Name | invoice | {"alias": "bill"}
(2 rows)
mix ecto.gen.migration create_names
defmodule Namely.Repo.Migrations.CreateNames do
use Ecto.Migration
def change do
create table(:names) do
add :name, :string
add :description, :string
timestamps()
end
create unique_index(:names, [:name])
end
end
mix ecto.migrate
iex -S mix
iex> Name.create("destroy", "Remove a record leaving no trace")
iex> Name.create("save", "Persisting a record somewhere.")
iex> Name.create("delete", "Remove a record")
iex> Name.all
13:48:01.365 [debug] QUERY OK source="names" db=3.1ms
SELECT n0."name" FROM "names" AS n0 ORDER BY n0."name" []["delete", "destroy", "save"]
def create(name, description) do
%Name{}
|> Name.changeset(%{name: name, description: description})
|> Repo.insert
|> log_action("create_name", %{name: name})
end
defp log_action({:ok, name}, action, data) do
log_action(
name,
action,
name.name,
data)
end
defp log_action({:error, changeset} = answer, action, data) do
log_action(
answer,
"#{action}_failed",
changeset.changes[:name],
data) # TODO: seralize the changeset.errors
end
defp log_action(answer, action, entity_id, data) do
%Action{}
|> Action.changeset(
%{name: action,
entity_type: "Name",
entity_id: entity_id,
data: data})
|> Repo.insert!
answer
end

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store