Skip to content

Commit

Permalink
add context and seed tags, #14
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonLab committed Apr 20, 2020
1 parent e2ee3aa commit 14dc9b4
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 10 deletions.
20 changes: 11 additions & 9 deletions lib/app_api/captures/capture.ex
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,22 @@ defmodule AppApi.Captures.Capture do
end

defp parse_tags(params) do
(params["tags"] || "")
|> String.split(",")
|> Enum.map(&String.trim/1)
|> Enum.reject(&(&1 == ""))
|> insert_and_get_all()
tags =
(params["tags"] || "")
|> String.split(",")
|> Enum.map(&String.trim/1)
|> Enum.reject(&(&1 == ""))

insert_and_get_all(tags, params["id_person"])
end

defp insert_and_get_all([]) do
defp insert_and_get_all([], _id_person) do
[]
end

defp insert_and_get_all(names) do
maps = Enum.map(names, &%{text: &1})
defp insert_and_get_all(tags, id_person) do
maps = Enum.map(tags, &%{text: &1, id_person: id_person})
Repo.insert_all(Tag, maps, on_conflict: :nothing)
Repo.all(from t in Tag, where: t.name in ^names)
Repo.all(from t in Tag, where: t.name in ^tags)
end
end
58 changes: 58 additions & 0 deletions lib/app_api/tags.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
defmodule AppApi.Tags do
@moduledoc """
The Tags context.
"""

import Ecto.Query, warn: false
alias AppApi.Repo

alias AppApi.Tags.Tag

@doc """
Returns the list of tags.
## Examples
iex> list_tags()
[%Tag{}, ...]
"""
def list_tags do
Repo.all(Tag)
end

@doc """
Returns the list of tags created by a person
i.e. default tags
"""
def get_tags_by_id_person(id_person) do
query =
from t in Tag,
where: t.id_person == ^id_person,
order_by: [asc: t.text]

Repo.all(query)
end

@doc """
Returns the list of tags where the person is not defined
i.e. default tags
"""
def get_default_tags() do
query =
from t in Tag,
where: is_nil(t.id_person),
order_by: [asc: t.text]

Repo.all(query)
end

@doc """
Creates a tag.
"""
def create_tag(attrs \\ %{}) do
%Tag{}
|> Tag.changeset(attrs)
|> Repo.insert!()
end
end
1 change: 0 additions & 1 deletion lib/app_api/tags/tag.ex
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
defmodule AppApi.Tags.Tag do
use Ecto.Schema
import Ecto.Changeset
alias AppApi.Captures.Capture

schema "tags" do
field :text, :string
Expand Down
5 changes: 5 additions & 0 deletions priv/repo/seeds.exs
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,8 @@
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.

alias AppApi.Tags

Tags.create_tag(%{text: "note", id_person: nil})
Tags.create_tag(%{text: "task", id_person: nil})

0 comments on commit 14dc9b4

Please sign in to comment.